maria
maria

Reputation: 159

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);
    });
}

Upvotes: 2

Views: 176

Answers (3)

Flint
Flint

Reputation: 1691

If you are looking for the sum of all the minions attacks, you can also perform it directly with mongo in one aggregation :

minion.aggregate(
   [{
      $group:{
        _id: null, 
        total:{$sum:"$attack"}
      }
   }]
).then( etc.. )

Upvotes: 1

Flint
Flint

Reputation: 1691

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 :
        minionsIds.forEach(function(mids) {
            console.log("sending one now");
            queries$p.push(minions.findById(mids).exec())
        });

        Promise.all(queries$p)
         .then( function(minions) { 
            minions.forEach(function(minion){ 
                total += minion.attack;
            })
            console.log("total attack:", total);       
            return resolve(total)
         })
         .catch( function(e) {
            return resolve(0)
         })
         ;
    });
}

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.

Upvotes: 1

Tommy
Tommy

Reputation: 134

you make another async call from

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

you should take all the ids in one time. i think you use mongodb here? use $in then you didnt need the for loop.

mongodb $in

Upvotes: 0

Related Questions