【发布时间】: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