Correct way to write loops for promise.

Wednesday, July 9, 2014

How to correctly construct a loop to make sure the following promise call and the chained logger.log(res) runs synchronously through iteration? (bluebird)



db.getUser(email).then(function(res) { logger.log(res); }); // this is a promise


I tried the following way (method from http://ift.tt/1cTGxrm )



var Promise = require('bluebird');

var promiseWhile = function(condition, action) {
var resolver = Promise.defer();

var loop = function() {
if (!condition()) return resolver.resolve();
return Promise.cast(action())
.then(loop)
.catch(resolver.reject);
};

process.nextTick(loop);

return resolver.promise;
});

var count = 0;
promiseWhile(function() {
return count < 10;
}, function() {
return new Promise(function(resolve, reject) {
db.getUser(email)
.then(function(res) {
logger.log(res);
count++;
resolve();
});
});
}).then(function() {
console.log('all done');
});


Although it seems to work, but I don't think it guarantees the order of calling logger.log(res);


Any suggestions?







http://ift.tt/1oHFU9E