Node.js,等待所有Redis查询完成后再继续执行

Ili*_*ija 2 javascript asynchronous node.js

我需要浏览一系列值,在Redis中查找日期(查看它是否存在),然后继续.例如:

var to_check = [ 1, 2, 3 ]
var found_elements = []

for (var i = 0; i < to_check.length; i++) {
  redis.EXISTS('namespace:' + to_check.length[i], function(err, value) {
    if (!err && value) {
      found_elements.push(to_check.length[i])
    }
  })
}

console.log(found_elements.join(', '))
Run Code Online (Sandbox Code Playgroud)

在发送到Redis的所有回调都已执行后,我需要执行最后一行.什么是最好的方法来解决这个问题?

Lew*_*wis 5

使用Promise处理复杂的异步操作.并行执行就是其中之一.

var to_check = [ 1, 2, 3 ];
var found_elements = [];
Promise.all(to_check.map(function(item){
    return new Promise(function(resolve,reject){
        redis.EXISTS('namespace:' + item, function(err, value) {
            if(err){
                return reject(err);
            }
            if (value) {
                found_elements.push(item);
            }
            resolve();
        })
    });
})).then(function(){
    console.log('All operations are done');
}).catch(function(err){
    console.log(err);
});
Run Code Online (Sandbox Code Playgroud)