简体   繁体   English

不使用async / await,顺序执行promises数组

[英]Execute an Array of promises sequentially without using async/await

Lets say I have an array of promises. 让我们说我有一系列的承诺。 Each element of my array is a knex.js query builder and is ready to be executed and returns a promise. 我的数组的每个元素都是一个knex.js查询构建器,可以执行并返回一个promise。

How can I run each element of this array sequentially. 如何顺序运行此数组的每个元素。 The array is built dynamically. 该数组是动态构建的。

let promisesArray = [q1,q2,q3] ;

Each q is not a promise by itself but it will return a promise upon execution. 每个q本身不是一个承诺,但它会在执行时返回一个承诺。

Here could be a possible option: 这可能是一个可能的选择:

let p = Promise.resolve([]);
promisesArray.forEach(q => {
  p = p.then(responses => {
    //based on the nature of each q, to start execution
    //use either q().then() or q.then()
    return q().then(response => {
      //Any further logic can be here.
      console.log(response);
      return responses.concat([response]);
    })
  })
})

p.then(responses => {
  // here you have all of the responses.
})

You can use Array.reduce to reduce the Array into one promise that chains them one after another 您可以使用Array.reduce将Array减少为一个接一个地链接它们的promise

let promisesArray = [q1,q2,q3] ;

function runSequentially(promiseArr) {
  return promiseArr.reduce((accum, p) => accum.then(p), Promise.resolve())
}

//Example, this prints.. 1, 2, 3 then "done".
runSequentially([Promise.resolve(1).then(console.log), Promise.resolve(2).then(console.log), Promise.resolve(3).then(console.log)]).then(() => console.log("done"))

I can think of bluebird promise, which should solve your issue. 我能想到蓝鸟的承诺,这应该可以解决你的问题。 Keeping the concurrency value to 1, should execute promises sequentially. 将并发值保持为1,应该按顺序执行promise。

    var Promise = require("bluebird");
    Promise.map([q1,q2,q3], {concurrency: 1})

Based on your claim that q1, q2, q3 are "knex.js query builder and is ready to be executed and returns a promise", get a function to execute itself with the next index when the promise is resolved. 根据您声称q1,q2,q3是“knex.js查询构建器并准备好执行并返回一个promise”的声明,获取一个函数,以便在解析promise时使用下一个索引执行自身。 Call it with 0 first. 先用0调用它。

function awaitPromise(arr, idx) {

   arr[idx]().then(function(res) {

       console.log(res);

       if (idx < arr.length - 1)      
           awaitPromise(arr, idx + 1);
   })
}

You can use Promise.map with concurrency set to 1 . 您可以将Promise.map与并发设置为1

await Promise.map(arrayOfObj, async (obj) => {
    await this.someOperation();
  },
  {concurrency: 1}
);

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

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