简体   繁体   English

javascript中promise数组的链式执行

[英]Chain execution of array of promises in javascript

I am trying to create a chain of promises where each promise waits for the previous promise before getting executed.我正在尝试创建一个承诺链,其中每个承诺在执行之前等待前一个承诺。

 const syncStatusChanges = () => { return new Promise((resolve, reject) => { console.log("in") setTimeout(() => { console.log("done") resolve({ done: true }) }, 2000); }); } const run = () => { const promises = [syncStatusChanges(), syncStatusChanges()] promises[0].then(res => { console.log("done 1") promises[1].then(res => { console.log("done 2") }) }) } run()

In this example the output is:在这个例子中,输出是:

in
in
done
done 1
done
done 2

But I want it to be:但我希望它是:

in
done
done 1
in
done
done 2

I also want it to work for any n number of functions.我还希望它适用于任意数量的函数。 I saw this answer but the output is the same!我看到了这个答案,但输出是一样的!

var promise = statusChangeCalls[0];
for (var i = 1; i < statusChangeCalls.length; i++)
    promise = promise.then(statusChangeCalls[i]);

As it is written in comments.正如评论中所写。 You are executing the functions in the array itself.您正在执行数组本身中的函数。 What i understood by seeing your output.看到你的输出,我明白了什么。 below run function can help you.下面的运行功能可以帮助你。

  const run = () => {
  const promise = syncStatusChanges();
  promise.then(res => {
     console.log("done 1")
     syncStatusChanges().then(res => {
         console.log("done 2")
     })
  })
}

Promise executes eagerly. Promise 急切地执行。 It does not wait to register the then function.它不会等待注册 then 函数。 You can look for observable , they are lazy in execution.你可以寻找observable ,它们在执行上很懒惰。 Basically they wait until you subscribe them.基本上他们会等到你订阅他们。

For your second doubt about loop.关于循环的第二个疑问。 You can use async await keyword to achieve chaining.您可以使用async await关键字来实现链接。 Just pass number as an parameter in runInLoop function to execute promise that many times.只需在 runInLoop 函数中传递 number 作为参数即可多次执行 promise。

const runInLoop = async(numberOfPromisesCall)=> {
  for (let i = 0; i < numberOfPromisesCall; i++){
       await syncStatusChanges();
       console.log(`done ${i + 1}`);
  }
} 
runInLoop(5)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM