问题
What's the best way to wait for all promises to finish in nodejs with bluebird? Lets say I want to select records from database and store them in redis. I came up with this
loadActiveChannels: function() {
return Knex('game_channels as ch')
.where('ch.channel_state', '>', 0)
.then(function(channels) {
var promises = [];
for(var i=0; i<channels.length; i++) {
var promise = redis.hmsetAsync("channel:"+channels[i].channel_id, _.omit(channels[i], 'channel_id'))
promises.push[promise];
}
return Promise.all(promises);
}).then(function(res) {
console.log(res);
})
}
Not sure if it's working as I expect. All entries are in redis but console.log shows empty array. Shouldn't it contain an array of 'OK' as it's the message redis returns after fulfilling the promise? What am I missing here?
回答1:
.map
is handy here:
loadActiveChannels: function() {
return Knex('game_channels as ch')
.where('ch.channel_state', '>', 0)
.map(function(channel) {
return redis.hmsetAsync("channel:"+channel.channel_id, _.omit(channel, 'channel_id'))
}).then(function(res) {
console.log(res);
})
}
The reason you don't get any output with your original code is because you have promises.push[promise];
which should have been promises.push(promise)
来源:https://stackoverflow.com/questions/21511578/wait-for-all-promises-to-finish-in-nodejs-with-bluebird