简体   繁体   English

我可以在异步 function 中使用 await async 吗?

[英]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:我是一个学习 promises 和 async/await 的新手,想知道是否可以更改此代码:

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不使用 setTimeout,因为它不返回任何内容,但使用真正的异步方法,您可以使用Promise.all

The Promise.all() method returns a single Promise that fulfills when all of the promises passed as an iterable have been fulfilled Promise.all()方法返回单个Promise ,当所有作为可迭代传递的承诺都已实现时,该 ZA5A3F0F287A4779AZ 实现

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

The short answer is yes .简短的回答是肯定的。 Awaiting anything turns it into a promise.等待任何东西都会把它变成 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 foo()本质上被包裹着类似的东西

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. async / await允许人们以更程序化的方式表达事物。 It also surrenders the event loop: other things can continue to process while you're waiting.它还放弃了事件循环:在您等待时,其他事情可以继续处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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