Keyur Sakaria Keyur Sakaria - 6 months ago 31
Javascript Question

Looping with promise bluebird

Is there any way to loop the promise by number like

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


So the above code will loop 5 times

Right now promise expects an array

Tex Tex
Answer

One option: Promise.map(Array.from(Array(5).keys()), function(i){})

Basically, you're looking for the range() method, or at least a way to emulate it. If the Promise implementation you're using doesn't offer a range() method (and the most excellent bluebird Promise library doesn't), the code I provided above is a pretty concise way of emulating it.

Other options:

//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)
var myRange = i => Array.from(Array(i).keys())
Promise.map(myRange(5), function(i){})