简体   繁体   中英

Javascript Async/Await program order

 const function1 = () => new Promise(function(resolve,reject) { setTimeout(() => { resolve(10) },6000) }); const function2 = async () => { console.log("first"); const val = await function1() console.log("second"); return val } console.log("third -- " ,function2()) 

I was exepecting the order of the message as below:

first
second
third -- Promise { <pending> }>

But it turns out to give the below output:

first 
third -- Promise { <pending> }
second

can anyone please help me understanding this ?

rather than calling function2() you need to await on it

    await function2(); // logs first (6 seconds expire) second, 10

this is because you need to wait for function 2 to resolve the Promise before proceeding

you could do the following for the desired result

    const function3 = async () => {
        const third = await function2();
        console.log( "third --", third ) 
    }
    function3();

Try next code

const function1 = () =>
  new Promise(function (resolve, reject) {
    setTimeout(() => {
      resolve(10)
    }, 6000)
  });

const function2 = async () => {
  console.log("first");

  const val = await function1()
  console.log("second");
  return val;
}

const start = async () => {
  console.log("third -- ", await function2());
};

start();

It's in the logs buddy :)!

The log with the word third is logged second. Because the log with the word ' second ' is resolved inside function2 which is called as a normal function . This code basically assumes you're not interested in the (async) result of function two, so it just retuns the pending promise.

Whenever you want the result (and not the pending promise) of an async function you should always await it of chain a then() where you can log the final result, which in this case is 10.

explanation of your code

  1. console.log("first"); - goes first, I hope that there is no questions

  2. when interpretator see this line const val = await function1() - it waits here and continue to execute synchronous code with is console.log("third -- " ,function2()) and you can see third -- Promise { <pending> }

  3. than promise is resolving and execution of async part continues and you finally can see console.log("second");

to achieve expected behavior try this:

 const function1 = () => new Promise(function(resolve,reject) { setTimeout(() => { resolve(10) },6000) }); const function2 = async () => { console.log("first"); const val = function1() console.log("second"); return val } console.log("third -- " , function2()) 

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