简体   繁体   中英

Can I use await async inside an async function?

I'm an a newbie studying promises and async/await and would like to know if it's possible to change this code:

async function waiting() {
   let a = await new Promise(r => setTimeout(() => r('A'), 1e3))
   let b = await new Promise(r => setTimeout(() => r('B'), 2e3))
   let c = await new Promise(r => setTimeout(() => r('C'), 3e3))
   console.log(a, b, c)
}

waiting()

And use something like this:

let a = await async () => setTimeout(() => 'A', 1e3)

or similiar.

Update :

I also tried this:

let a = await (() => setTimeout(() => 'A', 1e3))()

I want to achieve the same with a shortened syntax.

Not with setTimeout as it doesn't return anything, but with real async methods you can use Promise.all

The Promise.all() method returns a single Promise that fulfills when all of the promises passed as an iterable have been fulfilled

let [a, b, c] = await Promise.all([methodA(), methodB(), methodC()]);

The short answer is yes . Awaiting anything turns it into a promise. You could say something like

// not asynchronous; not a promise
function foo() { return 3; }
. . .
async function do_it() {
  const x  = await foo();
}

foo() essentially gets wrapped with something like

new Promise( (resolve, reject) => {
  try {
    resolve(foo());
  } catch (err) {
    reject(err);
  }
}

So you could say something like:

const sleep = ms  => new Promise( resolve => setTimeout( () => resolve(), ms) );

async function waiting() {

   await sleep(1000);
   const a = await computeA();
   await sleep(2000);
   const b = await computeB();
   await sleep(3000);
   const c = await computeC();

   console.log(a, b, c)

}

async / await allows one to express things in a more procedural looking manner. It also surrenders the event loop: other things can continue to process while you're waiting.

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