javascript - 如何按顺序运行一系列 Promise

标签 javascript arrays node.js asynchronous promise

我需要对一组项目运行一些 promise ,但我不知道数组的长度。我如何按顺序运行这些 promise ?这就是我异步执行的方法:

const arrayABC = [a, b, c.....x, y, z] // length unknown
const promises = arrayABC.map(function(item) {
   doSomething(item)
   }
return Promise.all(promises)

我需要 promise 来一一落实。

最佳答案

假设我正确理解您的设置,这似乎是最合理的方法:

// return the promise chain from last element
return arrayABC.reduce(function (chain, item) {
  // bind item to first argument of function handle, replace `null` context as necessary
  return chain.then(doSomething.bind(null, item));
// start chain with promise of first item
}, doSomething(arrayABC.shift()));

关于javascript - 如何按顺序运行一系列 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42428187/

相关文章:

angularjs - 使用 Node.js Angular 和 socket.io 后端 mysql 和 php 进行实时股票观察

javascript - 将图像的值通过modal传递到另一个页面

javascript - JS - 如何删除使用 substr() 函数生成的字符串中间以外的所有空格?

php - 如何设置从MySQL数组获取多个值并检查数组键

python - 通过减法折叠数组后找到最大结果

javascript - Promise 链中的 for 循环中的 Promise

node.js - 如何通过 SSH 连接到 Node 容器应用程序?

javascript - 使用 Jquery 解析 xml 并出现错误

javascript - 如何将字符串循环为键值对

javascript - 将新对象插入多维数组