等待所有答应与bluebird在nodejs中完成 [英] wait for all promises to finish in nodejs with bluebird

查看:63
本文介绍了等待所有答应与bluebird在nodejs中完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用bluebird等待所有承诺在nodejs中完成的最佳方法是什么?可以说我想从数据库中选择记录并将其存储在Redis中.我想出了这个

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

不确定它是否按预期工作.所有条目都在redis中,但console.log显示为空数组.它不应该包含一个"OK"数组,因为这是兑现承诺后redis返回的消息吗?我在这里想念什么?

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?

推荐答案

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

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)

这篇关于等待所有答应与bluebird在nodejs中完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆