如何在循环内完成异步函数后调用函数? [英] How to call function after completion of async functions inside loop?

查看:44
本文介绍了如何在循环内完成异步函数后调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 NodeJS 中有一个 forEach 循环,它迭代一系列键,然后从 Redis 异步检索这些键的值.循环和检索完成后,我想将该数据集作为响应返回.

I have a forEach loop in NodeJS, iterating over a series of keys, the values of which are then retrieved asynchronously from Redis. Once the loop and retrieval has complete, I want to return that data set as a response.

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

My problem at the moment is because the data retrieval is asyncrhonous, my array isn't populated when the response is sent.

如何在 forEach 循环中使用承诺或回调来确保响应与数据一起发送?

How can I use promises or callbacks with my forEach loop to make sure the response is sent WITH the data?

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

推荐答案

我在这里使用 Bluebird promises.请注意代码的意图是如何相当清晰并且没有嵌套.

I use Bluebird promises here. Note how the intent of the code is rather clear and there is no nesting.

首先,让我们承诺hgetall 调用和客户端 -

First, let's promisify the hgetall call and the client -

var client = Promise.promisifyAll(client);

现在,让我们用 Promise 编写代码,.then 而不是使用 .map 的节点回调和聚合..then 的作用是发出异步操作完成的信号..map 接受一组事物并将它们全部映射到异步操作,就像您的 hgetall 调用一样.

Now, let's write the code with promises, .then instead of a node callback and aggregation with .map. What .then does is signal an async operation is complete. .map takes an array of things and maps them all to an async operation just like your hgetall call.

注意 Bluebird 如何添加(默认)Async 后缀到promisifed 方法.

Note how Bluebird adds (by default) an Async suffix to promisifed methods.

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

这篇关于如何在循环内完成异步函数后调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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