1 回答
TA贡献1995条经验 获得超2个赞
await foo(); await bar();
仅在解决了返回的 Promise后才会调用bar
(从而创建第二个 Promise)。foo
var x = foo(); var y = bar(); await x;
在解决返回的承诺之前调用bar
(从而创建第二个承诺) 。foo
这就是承诺“同时”的原因。如果您在不同的地方添加,console.log
您将看到执行上的差异:
function timeoutPromise(name, interval) {
return new Promise((resolve, reject) => {
console.log(`Promise ${name} created.`);
setTimeout(function(){
console.log(`Promise ${name} resolved.`);
resolve("done");
}, interval);
});
};
async function timeTest1() {
console.log('test 1');
await timeoutPromise(1, 3000);
console.log('between promise 1 and 2');
await timeoutPromise(2, 3000);
}
async function timeTest2() {
console.log('test 2');
const timeoutPromise1 = timeoutPromise(1, 3000);
console.log('between promise 1 and 2');
const timeoutPromise2 = timeoutPromise(2, 3000);
await timeoutPromise1;
console.log('between promise 1 and 2 with await');
await timeoutPromise2;
}
timeTest1().then(timeTest2);
添加回答
举报