【问题标题】:When is `await` resolved simultaneously?`await` 什么时候同时解决?
【发布时间】:2018-04-13 06:04:32
【问题描述】:

async function 的 MDN 文档目前给出了以下两种使用 await 的组合示例。为了强调,我重新排序了一点:

function resolveAfter2Seconds(x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(x);
    }, 2000);
  });
}


async function add1(x) {
  const a = await resolveAfter2Seconds(20);
  const b = await resolveAfter2Seconds(30);
  return x + a + b;
}

async function add2(x) {
  const p_a = resolveAfter2Seconds(20);
  const p_b = resolveAfter2Seconds(30);
  return x + await p_a + await p_b;
}


add1(10).then(v => {
  console.log(v);  // prints 60 after 4 seconds.
});

add2(10).then(v => {
  console.log(v);  // prints 60 after 2 seconds.
});

这让我有点吃惊。为什么

const a = await resolveAfter2Seconds(20);
const b = await resolveAfter2Seconds(30);
return x + a + b;

依次解决两个promise,同时

return x + await p_a + await p_b;

似乎同时解决了两个承诺?这种行为是专门为await 指定的,还是其他原因的自然结果?

【问题讨论】:

  • 谢谢,不过,我想要一个包含更具体规则的参考。例如。显然“行”在这里是一种简化,尽管它可能与语言级别的语句有关?
  • A function with multiple await expressions in it will be suspended once at a time on each await expression until that Promise is settled, before unsuspending execution and moving onto the next await expression – not unlike the case we observe with generators and yield。来源:ponyfoo.com/articles/understanding-javascript-async-await
  • @Dez 嗯,但是当多个 await 语句出现在单个表达式/语句/___中时,您如何解释 NOT“一次一次”行为?
  • 等待是顺序的。在第二个示例中,两个 await 同时被触发。在第一个示例中,触发了一个 await,async 函数暂停直到解决,然后触发了第二个 async 函数。参考:exploringjs.com/es2016-es2017/…

标签: javascript async-await ecmascript-2017


【解决方案1】:
async function add2(x) {
  const p_a = resolveAfter2Seconds(20);
  const p_b = resolveAfter2Seconds(30);
  return x + await p_a + await p_b;
}

在此语句中,p_a 和 p_b 是并行启动的(即,一旦您生成了 Promise),因此当您等待 p_a 和 p_b 时,它们将显示为并行,而不是顺序。

要获得其他功能(await in series),您需要:

return x + await resolveAfter2Seconds(20) + await resolveAfter2Seconds(30);

【讨论】:

  • 啊,现在说得通了 :-) 它与异步函数调用的评估发生时间有关,而不是与 await 语句本身的语法/上下文有关。谢谢!
猜你喜欢
  • 2020-09-03
  • 2011-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-22
  • 1970-01-01
相关资源
最近更新 更多