gpt4 book ai didi

javascript - 在 for 循环中创建 promise 链

转载 作者:行者123 更新时间:2023-12-01 07:35:35 25 4
gpt4 key购买 nike

我希望下面的代码在控制台上打印一个数字,然后等待一秒钟,然后再打印另一个数字。相反,它会立即打印所有 10 个数字,然后等待 10 秒钟。创建行为如所述的 promise 链的正确方法是什么?

function getProm(v) {
return new Promise(resolve => {
console.log(v);
resolve();
})
}

function Wait() {
return new Promise(r => setTimeout(r, 1000))
}

function createChain() {
let a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
let chain = Promise.resolve();
for (let i of a) {
chain.then(()=>getProm(i))
.then(Wait)

}
return chain;
}


createChain();

最佳答案

您必须分配 .then 的返回值返回 chain :

chain = chain.then(()=>getProm(i))
.then(Wait)

现在你基本上会做
chain
.then(()=>getProm(1))
.then(Wait)
.then(()=>getProm(2))
.then(Wait)
.then(()=>getProm(3))
.then(Wait)
// ...

代替
chain
.then(()=>getProm(1))
.then(Wait)

chain
.then(()=>getProm(2))
.then(Wait)

chain
.then(()=>getProm(3))
.then(Wait)
// ...

你可以看到第一个实际上是一个链,而第二个是平行的。

关于javascript - 在 for 循环中创建 promise 链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44955463/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com