I have an array that need to append to a database, the condition is, element has to be appended one after another to make it work, following is my code, seems commands are not executed sequentially, what's wrong with my code:thanks.
var B = require('bluebird')
var appends = []
recs.forEach(function (item) {
appends.push(dao.append_rec_cartAsync(item))
})
B.all(appends).then(function () {
console.log('all done')
})
When you call dao.append_rec_cartAsync(item)
you're executing the asynchronous operation. Once it's started you can't really do anything about it running. Also note that Promise.all
does not do things sequentially but rather parallely.
var B = require('bluebird');
B.each(recs, function(item){ // note we use B.each and not forEach here
// we return the promise so it knows it's done
return dao.append_recs_cartAsync(item);
}).then(function(){
console.log("all done!")
});
Or in short: B.each(recs, dao.append_recs_cartAsync)