Promise.all() 推送异步承诺时未成功
Promise.all() not successful when pushing async promises
我有这两段代码:
A (https://repl.it/repls/HarmlessSupportiveUpgrades)
array = []
const promise = async (i) => console.log(i)
for (const num of [1, 2, 3, 4, 5]) {
array.push(promise(num))
}
Promise.all(array)
B(https://repl.it/repls/ColdHealthyAssignment)
array = []
for (const num of [1, 2, 3, 4, 5]) {
array.push(async (i) => console.log(i))
}
Promise.all(array)
我很困惑为什么 A 会成功打印到控制台,但 B 不会。怎么来的?
在第一个片段中,您使用 num 作为参数调用函数。
但是在第二个你将函数声明推送到数组
如果你替换
array.push(async (i) => console.log(i))
第二个片段
array.push((async (i) => console.log(i))(num))
它将以与第一个代码段相同的方式工作。
我有这两段代码:
A (https://repl.it/repls/HarmlessSupportiveUpgrades)
array = []
const promise = async (i) => console.log(i)
for (const num of [1, 2, 3, 4, 5]) {
array.push(promise(num))
}
Promise.all(array)
B(https://repl.it/repls/ColdHealthyAssignment)
array = []
for (const num of [1, 2, 3, 4, 5]) {
array.push(async (i) => console.log(i))
}
Promise.all(array)
我很困惑为什么 A 会成功打印到控制台,但 B 不会。怎么来的?
在第一个片段中,您使用 num 作为参数调用函数。
但是在第二个你将函数声明推送到数组
如果你替换
array.push(async (i) => console.log(i))
第二个片段
array.push((async (i) => console.log(i))(num))
它将以与第一个代码段相同的方式工作。