wait for all promises to finish in nodejs with bluebird

你说的曾经没有我的故事 提交于 2019-12-10 17:21:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!