如何调用函数完成后的异步函数内循环? [英] How to call function after completion of async functions inside loop?
问题描述
我在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循环中使用promises或回调以确保响应与数据一起发送?
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.
首先,让我们 promisify 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如何为promisifed方法添加 Async
后缀。
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屋!