简体   繁体   中英

Javascript Async Functions and Promises

Good afternoon in my timezone.

I have been reading about Promises and Async functions, and i come across a page where there is an example with code :

function doubleAfter2Seconds(x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(x * 2);
    }, 2000);
  });
}

async function addAsync(x) {
  const a = await doubleAfter2Seconds(10);
  const b = await doubleAfter2Seconds(20);
  const c = await doubleAfter2Seconds(30);
  return x + a + b + c;
}

var toLog = addAsync(10);
console.log(toLog);

I used the JSFiddle and the Chrome console : The "toLog" variable is a promise object with the promiseValue of 130.

Questions :

Inside the doubleAfter2Seconds function the sum is made inside the "resolve" function, if in the example we never pass the "resolve" function(through the then method in the promise object i think) how can we get the 130 result ?

Best regards Thanks in advance

Inside the doubleAfter2Seconds function the sum is made inside the "resolve" function

No.

The multiplication is performed inside the anonymous (arrow) function that is passed as the argument to Promise .

The result of that expression is immediately passed as the argument to the resolve function.

The resolve function is created by the Promise constructor and passed as the first argument to the (previously mentioned) anonymous function.

(And then that value is returned to a , b , or c via the await keyword.)

then doesn't directly connect to resolve . resolve is passed to the promise executor function (the function you pass to new Promise ) to be used to resolve the promise. then just hooks up handlers for promise resolution, which critically are not directly linked to that resolve function, but to the general operation of promises.

The reason you don't see any callback function in the addAsync function is that it's an async function using await . async / await is syntactic sugar for promise generation and consumption. Roughly speaking, if we remove that syntactic sugar, addAsync looks like this:

function addAsync(x) {
  return doubleAfter2Seconds(10)
    .then(a =>
        doubleAfter2Seconds(20)
            .then(b =>
                doubleAfter2Seconds(30)
                    .then(c => x + a + b + c)
            )
    );
}

or perhaps more readably (or not):

function addAsync(x) {
  return doubleAfter2Seconds(10)
    .then(a => {
        return doubleAfter2Seconds(20)
            .then(b => {
                return doubleAfter2Seconds(30)
                    .then(c => {
                        return x + a + b + c;
                    });
            });
    });
}

As you can see, we call doubleAfter2Seconds , wait for its promise to resolve, and receive that resolution value as a , then do the same and get the resolution as b , then again with c , and finally do the x + a + b + c when we have all the parts. The function returns a promise ( then creates a new promise, remember) which is resolved with that sum.

More on MDN:

The function doubleAfter2Seconds is called 3 times, and everytime it awaits that the Promise get back before keep on running the rest of the code

So the first time it is called, after 2 seconds:

a = 10 * 2 = 20

The second time, after other 2 seconds:

b = 20 * 2 = 40

The third time, after other 2 seconds:

c = 30 * 2 = 60

The function is called by AddAsync, so x will be 10

The final result is computed as:

a + b + c + x = 20 + 40 + 60 + 10 = 130

In case you don't want to pass the resolve function and use then you need to nest the function doubleAfter2Seconds

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM