在for循环中创建一个promise链 [英] Creating a promise chain in a for loop

查看:188
本文介绍了在for循环中创建一个promise链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would expect the code below to print one number on the console, then wait a second and then print another number. Instead, it prints all 10 numbers immediately and then waits ten seconds. What is the correct way to create a promise chain that behaves as described?

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();


推荐答案

您必须指定<$ c的返回值$ c> .then 返回

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)
// ...

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

You can see that the first one is actually a chain, while the second one is parallel.

这篇关于在for循环中创建一个promise链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆