wait
函数用作 sleep 函数,fn
函数接受一个数组(项目),它记录每个项目并在记录下一个项目之前休眠一秒钟.
const wait = async(time) => {
return new Promise((resolve) => setTimeout(resolve, time))
}
const fn = async(items) => {
for (item of items) {
await wait(1000)
console.log(item)
}
}
const exeAll = async() => {
Promise.all([
fn(['A1', 'A2']),
fn(['B1', 'B2']),
])
}
exeAll()
问题是 exeAll
函数提供的打印结果:
B1
A2
B2
B2
但我认为它应该打印如下内容:
A1
B1
A2
B2
执行上述代码时,A1 根本不显示。谁能解释为什么?
最佳答案
for (item of items) {
会创建一个隐式全局变量item
,即多次调用fn
会互相干扰,覆盖 item
。正确声明变量,它按预期工作:
const wait = async(time) => {
return new Promise((resolve) => setTimeout(resolve, time))
}
const fn = async(items) => {
for (let item of items) {
// ^^^^
await wait(1000)
console.log(item)
}
}
const exeAll = async() => {
Promise.all([
fn(['A1', 'A2']),
fn(['B1', 'B2']),
])
}
exeAll()
我们可以向 fn
添加更多日志记录,以查看在您的情况下会发生什么:
const wait = async(time) => {
return new Promise((resolve) => setTimeout(resolve, time))
}
let counter = 0;
const fn = async(items) => {
const c = counter++;
console.log(`enter fn call #${c}`);
for (item of items) {
console.log(`fn call #${c} sets item <-`, item);
await wait(1000)
console.log(`fn call #${c} reads item ->`, item);
console.log(item)
}
}
const exeAll = async() => {
Promise.all([
fn(['A1', 'A2']),
fn(['B1', 'B2']),
])
}
exeAll()
严格模式 ("use strict";
) 会发现该错误,因为分配给未声明的变量会引发错误。
关于javascript - Promise.all() 中的第一个 promise 没有正确执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69094022/