fee*_*lay 3 javascript asynchronous promise
在某些情况下使用 async/await 比使用 Promise 慢吗?
考虑使用 promise 的此类代码
function foo() {
const p1 = new Promise(res => setTimeout(() => res('first'), 2000));
const p2 = new Promise(res => setTimeout(() => res('second'), 2000));
p1.then(console.log);
p2.then(console.log);
}
foo()
Run Code Online (Sandbox Code Playgroud)
2000 毫秒后'first',然后'second'打印到控制台。
使用 async/await 的相同代码
async function foo() {
const p1 = await new Promise(res => setTimeout(() => res('first'), 2000));
const p2 = await new Promise(res => setTimeout(() => res('second'), 2000));
console.log(p1);
console.log(p2);
}
foo();
Run Code Online (Sandbox Code Playgroud)
使用 async/await 打印'first'和等待需要 4000 毫秒'second'
你相当于第一个片段async / await是错误的,应该是:
async function foo() {
const p1 = new Promise(res => setTimeout(() => res('first'), 2000));
const p2 = new Promise(res => setTimeout(() => res('second'), 2000));
const result = await Promise.all([p1,p2]);
console.log(result[0]);
console.log(result[1]);
}
foo();Run Code Online (Sandbox Code Playgroud)
您拥有的第一个代码段同时运行承诺,第二个是同步运行。这就是为什么await应该以良好的谨慎和知识使用。
警告
正如@Bergi 所指出的,请记住Promise.all要么全有要么全无,因此如果一个承诺失败,它将立即拒绝,而在您的第一个代码段中并非如此。