小编典典

循环内异步函数完成后如何调用函数?

redis

我在NodeJS中有一个forEach循环,遍历一系列键,然后从Redis异步检索其值。循环和检索完成后,我想返回该数据集作为响应。

我目前的问题是因为数据检索是异步的,发送响应时没有填充我的数组。

如何在我的forEach循环中使用promise或回调,以确保响应与数据一起发送?

exports.awesomeThings = function(req, res) {
    var things = [];
    client.lrange("awesomeThings", 0, -1, function(err, awesomeThings) {
        awesomeThings.forEach(function(awesomeThing) {
            client.hgetall("awesomething:"+awesomeThing, function(err, thing) {
                things.push(thing);
            })
        })
        console.log(things);
        return res.send(JSON.stringify(things));
    })

阅读 383

收藏
2020-06-20

共1个答案

小编典典

我在这里使用Bluebird
Promise
。请注意,代码的意图非常清晰并且没有嵌套。

首先,让我们讲解 hgetall调用和客户端-

var client = Promise.promisifyAll(client);

现在,让我们用promise编写代码,.then而不是用进行节点回调和聚合.map。什么.then确实是信号的异步操作完成。.map接受一系列事物并将它们全部映射到异步操作,就像您的hgetall调用一样。

请注意,Bluebird如何(默认情况下)向Async后缀方法添加后缀。

exports.awesomeThings = function(req, res) {
    // make initial request, map the array - each element to a result
    return client.lrangeAsync("awesomeThings", 0, -1).map(function(awesomeThing) {
       return client.hgetallAsync("awesomething:" + awesomeThing);
    }).then(function(things){ // all results ready 
         console.log(things); // log them
         res.send(JSON.stringify(things)); // send them
         return things; // so you can use from outside
    });
};
2020-06-20