与承诺蓝鸟循环

Looping with promise bluebird

有没有办法像

一样按数字循环承诺
Promise.map(5, function(i){})

所以上面的代码会循环5次

现在 promise 需要一个数组

一个选项:Promise.map(Array.from(Array(5).keys()), function(i){})

基本上,您正在寻找 range() 方法,或者至少是一种模拟它的方法。如果您使用的 Promise 实现不提供 range() 方法(并且最优秀的 bluebird Promise 库不提供),我上面提供的代码是一种非常简洁的模拟方法。

其他选项:

//If you're using lodash, underscore or any other library with a .range() method
Promise.map(_.range(5), function(i){})

//Or write your own reusable range() function
// ES6 arrow function syntax
var myRange = i => Array.from(Array(i).keys())
// or classic function syntax
var myRange = function (i) {return Array.from(Array(i).keys())}

Promise.map(myRange(5), function(i){})