From the tutorial:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await
function resolveAfter2Seconds(x) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
async function f1() {
const x = await resolveAfter2Seconds(10);
console.log(x); // 10
}
f1();
I can see 10
going all the way into the resolve(x)
, but it doesn’t seem going out from the resolve
function. The document says Promise.resolve
returns another Promise
, but I don’t see any code taking this new Promise
. I also don’t see any code returning the x
to the outer scope. The document doesn’t seem explaining this, or I just don’t understand.
How does the await
keyword know that the return value is 10
?
2
Answers
Because
resolve
sets the promise’s resolved value to what you pass to it, andawait
awaits until a promise is resolved (or rejected) and returns the resolved value (or throws, if the promise was rejected).Promise.resolve
is a different beast – it returns a promise that’s already resolved.Since you’re passing a new function of your own devising to
new Promise
, you could name thatresolve
e.g.ok
, if it makes things clearer:new Promise((ok) => ok(8))
(but please don’t; the convention isresolve
).You don’t really need to know what exactly happens internally in your JavaScript engine for promises to work.
Do not confuse the static
resolve
method of thePromise
class with the function passed as the first argument to the function passed to thenew Promise
constructor.Because
x
isn’t returned.You can’t return from an asynchronous operation. That is why promises exist in the first place.
resolveAfter2Seconds
returns a promise.That promise is resolved with the value of
x
.await
sendsf1
to sleep until the promise on its RHS resolves.When it does, it becomes the resolved value which is assigned to the other
x
.