Kind of stuck on this one. Working with https://github.com/then/promise on node.js
exports.count = function ( models, callback ) {
var promises = [];
models.forEach(function ( name ) {
promises.push( countOne( name ) );
});
Promise.all( promises ).then(function ( res ) {
callback( null, res );
});
Promise.resolve(promises[0]).then(function (res) {
console.log('resolved individual with res', res);
});
};
function countOne ( exampleArg ) {
return new Promise(function ( resolve, reject ) {
// It resolves or rejects
});
}
I've also tried:
Promise.all( promises.map(function ( it ) { return Promise.resolve(it); }) ).then(function ( res ) {
callback( null, res );
});
Either way, Promise.all doesn't fire the then. Promise.resolve does, however, give the appropriate response.
ether one of your promises isn't resolving, in which case, your need to find out which one.
I think you are trying to do that with that console.log
. if you do that with a forEach you can attach a log message to all promises and see which one isn't resolving / rejecting.
Or one of the promises is rejecting, which you are not handling.
I took the liberty of rewriting your code, try it like this:
exports.count = function (models, callback) {
var allCounts = models.map(countOne);
// second parameter is the onRejected handler
Promise.all(allCounts).then(function (res) {
callback(null, res);
}, function (err) {
callback(err);
});
promises[0].then(function (res) {
console.log('resolved individual with res', res);
});
};
I left in the callback, but I really would just return the promise, much simpler, much cleaner.
ProTip™:
Switch to the bluebird promise library, and replace your implementation with one line:
exports.count = function (models, callback) {
Promise.map(models, countOne).nodeify(callback);
}
It will probably be faster to.