【问题标题】:wait for all promises to finish in nodejs with bluebird等待所有承诺在 nodejs 中用 bluebird 完成
【发布时间】:2014-02-02 14:15:17
【问题描述】:

用 bluebird 在 nodejs 中等待所有 promise 完成的最佳方式是什么?假设我想从数据库中选择记录并将它们存储在 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在履行承诺后返回的消息?我在这里错过了什么?

【问题讨论】:

  • 顺便说一句,您可以将 for 循环替换为 .map()

标签: node.js redis promise bluebird


【解决方案1】:

.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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-09
    • 1970-01-01
    • 2017-06-17
    • 1970-01-01
    • 2018-03-05
    • 2016-10-16
    相关资源
    最近更新 更多