TLP*_*TLP 20 javascript es6-promise
我希望下面的代码在控制台上打印一个数字,然后等待一秒,然后打印另一个数字.相反,它立即打印所有10个数字,然后等待十秒钟.创建一个行为如上所述的承诺链的正确方法是什么?
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();
Run Code Online (Sandbox Code Playgroud)
Fel*_*ing 25
您必须将返回值分配.then
回chain
:
chain = chain.then(()=>getProm(i))
.then(Wait)
Run Code Online (Sandbox Code Playgroud)
现在你基本上会这样做
chain
.then(()=>getProm(1))
.then(Wait)
.then(()=>getProm(2))
.then(Wait)
.then(()=>getProm(3))
.then(Wait)
// ...
Run Code Online (Sandbox Code Playgroud)
代替
chain
.then(()=>getProm(1))
.then(Wait)
chain
.then(()=>getProm(2))
.then(Wait)
chain
.then(()=>getProm(3))
.then(Wait)
// ...
Run Code Online (Sandbox Code Playgroud)
你可以看到第一个实际上是一个链,而第二个是并行的.
归档时间: |
|
查看次数: |
9727 次 |
最近记录: |