rakesh kashyap
rakesh kashyap

Reputation: 1466

Async method inside Promise.map

I need help in understanding how to call an async method inside a .map method. I need to wait till all the async methods are completed, and then use the values the async method modified.

My code is as below

//declared during init
var Promise = require("bluebird");

Promise.map(objectArray, function (item) {

    mongoDB.findOne({
        itemId=item.id
    })
        .then(function (result) {
            item.set({newValue:result.foo});
            return item.toObject();
        })
        .catch(function (err) {

        });
}).then(function (modifiedObjectArray) {
    return res.status(200).send(modifiedObjectArray);
});

In the above case map's then function is called as soon as the iterator completes its task. How do I wait until all the DB tasks are completed.

Upvotes: 0

Views: 651

Answers (1)

Martin Adámek
Martin Adámek

Reputation: 18389

You should return the promise from your callback:

Promise.map(objectArray, function (item) {
    return mongoDB
        .findOne({itemId: item.id})
        .then(function (result) {
            item.set({newValue: result.foo});
            return item.toObject();
        })
        .catch(function (err) {

        });
}).then(function (modifiedObjectArray) {
    return res.status(200).send(modifiedObjectArray);
});

Upvotes: 1

Related Questions