maria maria - 3 months ago 9
Node.js Question

node/mongo response after loop

how would i return the total as resolve(total) when the loop is done?

what would be the way to do it?

function getTotalAttack(minions) {
return new Promise( function (resolve, reject) {
console.log("starting do the totalattack math");

var total = 0;
for(var minion in minions) {
console.log("sending one now");

minions.findOne({ _Id : minion }).then(function(response){
total = total + response.attack;
});

}
console.log("result is " + total);
return resolve(total);
});
}

Answer

You can use Promise.all()

function getTotalAttack(minionsIds) {
    return new Promise( function (resolve, reject) {

        var total = 0,
            queries$p=[]
        // if you need only to retrieve the documents :
        // queries$p = minions.find({_id:{$in:minionsIds}}).exec()

        // or if you need an extra instruction in between :
        for(var mids in minionsIds) {
            console.log("sending one now");
            queries$p.push(minions.findById(mids).exec())
        });



        Promise.all(queries$p).then( function(minions) { 
            for(var minion in minions) {
                total += minion.attack;
            }
            console.log("total attack:", total);       
            return resolve(total)
        });
    });
}

From the MDN :

Promise.all is rejected if one of the elements is rejected and Promise.all fails fast: If you have four promises which resolve after a timeout, and one rejects immediately, then Promise.all rejects immediately.

Comments