首页 文章

等待所有承诺在使用bluebird的nodejs中完成

提问于
浏览
4

什么是等待所有承诺在bluebird中完成nodejs的最好方法?假设我想从数据库中选择记录并将它们存储在redis中 . 我想出了这个

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);
    })
}

不确定它是否像我期望的那样工作 . 所有条目都在redis中,但console.log显示为空数组 . 它不应该包含一个'OK'数组,因为它是在履行承诺后redis返回的消息吗?我在这里错过了什么?

1 回答

  • 3

    .map 在这里很方便:

    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);
        })
    }
    

    您没有使用原始代码获得任何输出的原因是因为您有 promises.push[promise]; 应该是 promises.push(promise)

相关问题