skip to Main Content

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


  1. Because resolve sets the promise’s resolved value to what you pass to it, and await 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 that resolve e.g. ok, if it makes things clearer: new Promise((ok) => ok(8)) (but please don’t; the convention is resolve).

    You don’t really need to know what exactly happens internally in your JavaScript engine for promises to work.

    Login or Signup to reply.
  2. The document says Promise.resolve

    Do not confuse the static resolve method of the Promise class with the function passed as the first argument to the function passed to the new Promise constructor.


    I also don’t see any code returning the x to the outer scope

    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 sends f1 to sleep until the promise on its RHS resolves.

    When it does, it becomes the resolved value which is assigned to the other x.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search