简体   繁体   中英

Await behaviour within an async IIFE

I was trying to understand the behaviour of async/await and came up with this example

 function foo() { async function bar() { return new Promise((resolve)=> { setTimeout(()=> { resolve("Done"); }, 1); }); } (async function () { console.log("Calling bar..."); const res = await bar(); console.log("After bar..."); })(); } console.log("Calling foo..."); foo(); console.log("After foo...");

I was expecting the output to be

Calling foo...
Calling bar...
After bar...
After foo...

whereas the output is

Calling foo...
Calling bar...
After foo...
After bar...

Why doesn't the script execution wait on the const res = await bar(); statement but instead execute the console.log("After foo..."); ? Does the await inside an anonymous block lead to the deferral of the async code block somehow?

One way I tried to reason about this was that since await is built upon promise , it essentially changes the code to something like

 function foo() { async function bar() { return new Promise((resolve)=> { setTimeout(()=> { resolve("Done"); }, 1); }); } (async function () { console.log("Calling bar..."); const res = bar(); res.then(() => { console.log("After bar..."); }); })(); } console.log("Calling foo..."); foo(); console.log("After foo...");

which would possibly explain why the console.log("After bar..."); is executed after the console.log("After foo...");statement. Is that the right way to reason about this or is there something that I'm missing here?

Does the await inside an anonymous block lead to the deferral of the async code block somehow?

Yes.

 function takeOneTick(){ return new Promise((resolve,reject)=>setTimeout(resolve)); } async function foo(){ console.log("1"); await takeOneTick(); console.log("3"); } foo(); console.log("2");

Every async function returns a Promise. If you need the code to execute in order, then you await your async function.

 function takeOneTick(){ return new Promise((resolve,reject)=>setTimeout(resolve)); } async function foo(){ console.log("1"); await takeOneTick(); console.log("2"); } (async function(){ await foo(); console.log("3"); })();

Also, Returning a Promise from an async function is a Promise in a Promise (which won't do anything bad but there is no point).

Also Also, yes await is like putting the remainder of the function in a .then()

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