user6591146 user6591146 - 1 year ago 88
Node.js Question

Promise.all do not wait all promises to resolve

I need to get data in parallel, and then calculate with them simultaneously, with Node.js.

So I use promise.all, but it behaves strange. When I launch it the first time, the calculations are longer and it fails just after the first promise has resolved, even if the others succeed.
When I launch it the second time, it's faster because all data are stored in the database, so it succeeds.
I really don't understand. Here is my code :

var Promise = require('promise');
/* The list of objects */
var ingrd_list = JSON.parse(req.body.ingrd_list);
/* func.addFood is my function to apply on. It takes a callback parameter as last parameter */
var pAddFood = Promise.denodeify(func.addFood);
var pArray = [];

var my_p = pAddFood(ingrd);

console.log("success !");
console.log("failure !");

I have defined the addFood function in an other file, like this :

exports.addFood = function(ingrd, cb){
/* Some code */

I want to apply this function, so I tried to make it "denodeify-compatible".
But it doesn't work as expected.
Any help would be greatly appreciated

Answer Source

The problem is that denodeify expect your callback to be called in a standard way, that is callback(err, data)

but you are calling you callback with callback(data), so it is putting your promise in a rejected state, because it thinks that you data is in fact the error, thus Promise.all fails

To fix that you should modify you addFood function to call the callback like this cb(undefined,;

ps: you can look for "node style callback" if you want more detailed information about this callback style

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download