node.js - NodeJS: for loop and promises -
node.js - NodeJS: for loop and promises -
asynchronous programming much more hard synchronous programming.
using nodejs, trying following:
for (var = 0; < 10; i++) { somefunction().then(function() { // stuff }); }
but want loop go on when stuff part has completed.
any thought how can achieved...?
thank you!
async programming can confusing, of confusion can eliminated if maintain in mind things callbacks , then
run @ later time, after code block they're contained in has finished.
promise libraries, async
module, attempts more command on program's flow. here good article explaining different approaches, helped me understand things seeing different alternative solutions same problem.
a couple of other answers mention q.all()
. works well, if have array of promises.
if have array of values, or promises, there library makes easier, called bluebird
. has method called .map()
can utilize start promise chain array.
with approach don't need phone call asynchronous, promise-returning function, store returned promise in array, pass array q.all
. saves steps.
so, assuming have array of values:
var items = [0,1,2,3,4,5,6,7,8,9];
you can following:
promise.map(items, function (item) { homecoming performasyncoperation(item); }, {concurrency: n}) .then(function(allresults){ // 'allresults' contains array of // results of 'performasyncoperation' })
note: work expected, performasyncoperation
must homecoming promise
also note 3rd argument promise.map()
: {concurrency: n}
. alternative specified, bluebird allow n
operations performed @ time, can useful if have huge amount of items process overwhelm scheme if kicked off @ 1 time (network connections, filehandles, etc).
final note: here bluebird api doc. it's extremely written lots of examples, , great way explore how promises can help create life easier.
hope helps!!!
node.js promise
Comments
Post a Comment