Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

async and Q promises in nodejs

I'm using the Q library and async library in nodejs.

Here's 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 guess then() doesn't have access. Any ideas how to work around this?

like image 950
dzm Avatar asked Dec 16 '13 18:12

dzm


People also ask

What is difference between async and promise?

Promise is an object representing intermediate state of operation which is guaranteed to complete its execution at some point in future. Async/Await is a syntactic sugar for promises, a wrapper making the code execute more synchronously.

How do I use Q promise in node JS?

var Q = require('q'); // this is suppose, the async function I want to use promise for function async(cb) { setTimeout(function () { cb(); }, 5000); } async(function () { console. log('async called back'); }); How do I use Q and its .

Can we use async with promises?

async and awaitInside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.

What are the three states of promises in node JS?

A Promise is in one of these states: pending: initial state, neither fulfilled nor rejected. fulfilled: meaning that the operation was completed successfully. rejected: meaning that the operation failed.


1 Answers

Your issue doesn't lie with promises, it lies with your usage of async.

async.each(items, handler, finalCallback) applies handler to every item of the items array. The handler function is asynchronous, i.e. it is handed a callback, that it must call when it has finished its work. When all handlers are done, the final callback is called.

Here's how you'd fix your current issue:

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 don't need to use async for this particular piece of code: promises alone fill this job quite nicely, 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);
    }
)
like image 83
Paul Mougel Avatar answered Oct 11 '22 02:10

Paul Mougel