简体   繁体   中英

Nested async/await functions

I am trying to understanding how to use async/await in nested manner. In the example, I am calling function a() and inside that, I want to call b() and ensure that b() resolves before a(). The following is the code and although b() is called, it is not getting resolved.

 function a() { b(); return new Promise((resolve, reject) => { setTimeout(() => { resolve('resolved a'); }, 2000); }); } function b() { console.log('calling b'); return new Promise((resolve, reject) => { setTimeout(() => { resolve('resolved b'); }, 2000); }); } async function asyncCall() { console.log('calling'); const result = await a(); console.log(result); } asyncCall();

The output of the code above is:
"calling"
"calling b"
"resolved a" (This line shows up after 2 seconds )

Then, I changed to code to include async/await in a(), (everything else is the same)

 async function a() { await b(); return new Promise((resolve, reject) => { setTimeout(() => { resolve('resolved a'); }, 2000); }); } function b() { console.log('calling b'); return new Promise((resolve, reject) => { setTimeout(() => { resolve('resolved b'); }, 2000); }); } async function asyncCall() { console.log('calling'); const result = await a(); console.log(result); } asyncCall();

The output of the code above is:
"calling"
"calling b"
"resolved a" (This line shows up after 4 seconds [In the previous example it was 2 seconds])

But in both the case, ' resolved b ' is not getting printed.

I have 2 questions:

  1. How do I print ' resolved b '?
  2. Is it common to have cases like this where an async function (in this case, function "a"), is both the callee (it is called by asyncCall()) and the caller (it is calling b())?

How do I print 'resolved b'?

Your code as it stands completely ignores the resolved value of b . The first example ignores the promise entirely. The second example waits for the promise to resolve but does nothing with the resolved value (not even capture it in a variable).

You have to console.log() it like you did everything else you logged.

You could logthisvalue = await b() . You could b().then(logthisvalue => here) . You could modify b() so it logs its own value.

Is it common to have cases like this where an async function (in this case, function "a"), is both the callee (it is called by asyncCall()) and the caller (it is calling b())?

Yes.

The async and await keywords are tools to manage promises.

Top level await has poor support so, in general, you can only use await inside an async function.

You have to call an async function for it to do anything.

The async function has to get a promise to await from somewhere and usually that is by calling another function.

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