Async and Q promises in nodejs

I use the Q library and async in nodes.

Here is an example of my code:

async.each(items, cb, function(item) { saveItem.then(function(doc) { cb(); }); }, function() { }); 

saveItem is a promise. When I run this, I always get cb is undefined , I think then() does not have access. Any ideas how to get around this?

+6
source share
1 answer

Your problem is not related to promises, it is related to using async .

async.each(items, handler, finalCallback) applies a handler to each element of the items array. The handler function is asynchronous, i.e. She is given a callback that he should call when he has completed his work. When all handlers are executed, the final callback is called.

Here you can fix your current problem:

 var handler = function (item, cb) { saveItem(item) .then( function () { // all is well! cb(); }, function (err) { // something bad happened! cb(err); } ); } var finalCallback = function (err, results) { // ... } async.each(items, handler, finalCallback); 

However, you do not need to use async for this piece of code: promises to fill in this work yourself pretty well, especially with Q.all() :

 // Create an array of promises var promises = items.map(saveItem); // Wait for all promises to be resolved Q.all(promises) .then( function () { // all is well! cb(); }, function (err) { // something bad happened! cb(err); } ) 
+20
source

All Articles