为什么这两个await行并行执行?



在下面的代码中,c和c2变量都在等待不同的promise实例,并且应该串行运行,但是当运行时,程序在100毫秒内完成,而不是200毫秒。

function a1() {
return new Promise((x, y) => {
setTimeout(function () {
x(5);
}, 100);
});
}
async function run() {
let t1 = Date.now();
let b = a1();
let b2 = a1();
let c = await b;
let c2 = await b2;
console.log(Date.now() - t1);
}
run().then(function () {
console.log('@');
});

如果await被定义为一个串行操作,为什么这个行为是合法的?

在声明bb2时都调用a1()。因此,当您等待时,超时已经运行,并且它们每个都持有一个承诺,等待只是解析这些承诺。

如果您想看到完整的延迟,您应该将a1分配给b变量,然后在声明c时等待调用,或者简单地等待a1()两次。

let b = a1;
let b2 = a1;
let c = await b();
let c2 = await b2();

function a1() {
return new Promise((x, y) => {
setTimeout(function () {
x(5);
}, 100);
});
}
async function run() {
let t1 = Date.now();
let b = await a1();
let b2 = await a1();

console.log(Date.now() - t1);
}
run().then(function () {
console.log('@');
});