I'm playing around with promises in Node.js and am trying to use Promise.all. I'm pushing three functions that return a promise into an array and then calling Promise.all but the all's resolve is never hit. On the debugger, it also says that Promise.all is "undefined".
Why is Promise.all never returning and why does it show up as "undefined"?
Relevant part of the code:
var updates = [];
updates.push(data.updateItemCondition(characterID, specificItemID_toUse, newCondition));
updates.push(data.updateCharacterLoot(characterID, newValue));
updates.push(data.updateSharedLoot(lootUpdateChange));
Promise.all(updates).then(function (success) {
resolve("Item successfully used");
}, function (error) {
resolve("Failed to use item " + error.toString());
});
All three functions look something like the below and using the debugger I can see that all three resolves are hit (and all three corresponding files on io.writeFile are updated on disk)
data.updateSharedLoot= function (lootUpdateChange) {
return new Promise(function (resolve, reject) {
//some logic
io.writeFile(...,function(callbackSuccess){
resolve(callbackSuccess);
});
});
}
That's strange because I have Promise.all defined even on old Node 0.12. On Node 0.10 I have Promise not defined. I don't think there's a version with Promise but without Promise.all. Maybe you're doing:
Promise.all = undefined;
What you should have undefined is the resolve
function. Here:
Promise.all(updates).then(function (success) {
resolve("Item successfully used");
}, function (error) {
resolve("Failed to use item " + error.toString());
});
you don't have any resolve
to call. Don't you mean console.log?
Promise.all(updates).then(function (success) {
console.log("Item successfully used");
}, function (error) {
console.log("Failed to use item " + error.toString());
});
Also here:
data.updateSharedLoot= function (lootUpdateChange) {
return new Promise(function (resolve, reject) {
//some logic
io.writeFile(...,function(callbackSuccess){
resolve(callbackSuccess);
});
});
}
the first parameter to your callback is probably an error, so you should:
data.updateSharedLoot= function (lootUpdateChange) {
return new Promise(function (resolve, reject) {
//some logic
io.writeFile(...,function(error, callbackSuccess) {
if (error) {
reject(error);
} else {
resolve(callbackSuccess);
}
});
});
}
But still I would suggest using a promised version of I/O like fs-promise if you're doing promises anyway. Your function that returns a promise could be as simple as:
var fsp = require('fs-promise');
data.updateSharedLoot = function (lootUpdateChange) {
return fsp.writeFile(...);
};
See this answer for more details.