I have found something interesting while playing with Promises and awaits:
function returnPromise() {
return new Promise(resolve => {
setTimeout(() => {
resolve('result of promise');
}, 1000);
});
}
async function sth() {
let result = await returnPromise();
console.log('result: ', result);
console.log('flag 1');
}
sth();
In this first example, the result of the promise prints out correctly. However, consider the second example:
function returnPromise() {
return new Promise(resolve => {
setTimeout(() => {
resolve('result of promise');
}, 1000);
});
}
async function sth2() {
let result = returnPromise();
await result;
console.log('result: ', result);
console.log('flag 1');
}
sth2();
Here, the result is {} (which I think means the Promise is still pending). This doesn't make sense to me because I thought the line 'await result' was supposed to block till the Promise resolved.
My question is:
Thank you.
I thought the line 'await result' was supposed to block till the Promise resolved.
Well, it blocks further execution of that async function - but yes.
But the result is still a Promise.
await will take the thenable on its right side, wait for it to finish, and extract the resolve value from it. But the thenable will remain a thenable - it doesn't change the Promise itself (it doesn't change the Promise expression into the value it resolves to).
await someThenable
extracts the resolve value from someThenable, but someThenable remains a thenable - logging someThenable, whether before or after the await, will still log the thenable, and not the resolve value.
let result = returnPromise();
This line sets the value of result to be a reference to the Promise object. It does not automagically change to be the result of the awaited promise whenever you call await on it later on.
You can tell by the fact that there's still a waiting period that the await keyword is working. However, you're throwing away the result value.
await will give you and rvalue that you can assign to a variable:
let actualResult = await result;
// or
result = await result; // but you shouldn't do this