Promises in a for loop, do something when done

387 Views Asked by At

Basically, I'm trying to figure out a way to do a bunch of queries in a for loop and then do something once they've all completed.

I got it to work, but only because I used this great library that wraps all of mongodb with promises.

var mongo = require('mongod') 
var db = mongo('mongodb://localhost/builder', ['block''])
var block_ids = ['538d097bbb12479d0e9f70ab', '538ddc7d06c1f0fe296178b1'];

var prom = null;
var blocks = [];
for (i in block_ids) {
    var block_id = block_ids[i];
    prom = db.block.findOne({_id:db.ObjectId(block_id)})
    .then(function(results) {
        blocks.push(results);
    })
}
prom.done(function() {
    console.dir(blocks)
    console.log("DONE! " + blocks.length)
})

My question is this. How on earth can you do something like with WITHOUT promises?? It seems like it would be so hard!

2

There are 2 best solutions below

0
On BEST ANSWER

Stupid for loops

var mongo = require('mongod') 
var db = mongo('mongodb://localhost/builder', ['block''])
var block_ids = ['538d097bbb12479d0e9f70ab', '538ddc7d06c1f0fe296178b1'];


Q(block_ids.map(function(block_id) {
    return db.block.findOne({_id:db.ObjectId(block_id)});
})).all().done(function(blocks) {
    console.dir(blocks)
    console.log("DONE! " + blocks.length)
});

I got it to work, but only because I used this great library that wraps all of mongodb with promises.

In bluebird you could have just done promisifyAll(require("mongodb")) instead of waiting for someone to make a module.

0
On

You could just use a simple variable to count the number of responses like so:

var responses = 0;
var blocks = [];

for(var i=0; i<block_ids.length; i++) {
   var block_id = block_ids[i];
   db.block.findOne({_id:db.ObjectId(block_id)}, function (err, result) {
       if(err) {
         console.log(err);
       }
       responses++;
       blocks.push[result];

       if (responses === block_ids.length-1) {
           console.log('all find queries have responded');
           // do whatever
       }

   }
}