'JavaScript code does not output the result on the first attempt [duplicate]
When I run the script (see below), the first attempt fails to get the result,
the "result" variable outputs "underfined"
var result;
Promise.resolve('information')
.then(res => {return result=res})
result;
Attempt #1
On the second attempt , the values are already assigned
Question: How can I expect to assign a value to the "result" variable, without using setTimout and console.log
Waiting with a While loop
var result;
var finito = false;
Promise.resolve('information')
.then(res => {return result=res})
while(finito != true)
{
if (result != undefined)
{
result;
finito=true;
}
}
My question for Jay Surya:
This code does not work
My question for Azarro:
Solution 1:[1]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve
Promise.resolve returns a promise. If it's accompanied by a .then, it'll follow up on the .then() asynchronously (almost immediately, emphasis on almost) and resolve as a Promise.
If you want result to get the actual value then you'll have to either use await in order to force the code to act synchronously and wait on the promise's value.
async function someWrappedFunction() {
const result = await Promise.resolve('information');
}
Alternatively, you can move your code inside the .then block of Promise so that you're guaranteed a value in there.
Edit: Can you try the following:
var result;
var finito = false;
var result = await Promise.resolve('information');
while(finito != true)
{
if (result != undefined)
{
result;
finito=true;
}
}
Solution 2:[2]
Best Solution for this is to use async-await, Since you seem to need result for further operations. If you still want to use .then() approach, you will have to move your var result and all the subsequent steps which need result, into the .then()
Promise.resolve('information').then(res=>{
var result = res;
var finito=true;
//all that follows
})
But alternatively if you use async-await,
var result;
var finito = false;
result = await Promise.resolve('information');//the lines below will not be executed, until this promise resolves
while(finito != true)
{
if (result != undefined)
{
result;
finito=true;
}
}
Ofcourse, await can only be used inside a function marked as async.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Jay Surya |




