Ano*_*ous 3 javascript callback redis node.js promise
我在NodeJS中有一个forEach循环,迭代一系列键,然后从Redis异步检索其值.一旦循环和检索完成,我想将该数据集作为响应返回.
我目前的问题是因为数据检索是异常的,我的数组在发送响应时没有填充.
如何在forEach循环中使用promises或callback来确保响应是随数据一起发送的?
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));
})
Run Code Online (Sandbox Code Playgroud)
Ben*_*aum 11
我在这里使用Bluebird的承诺.注意代码的意图是如何清晰的,没有嵌套.
首先,让我们宣传 hgetall呼叫和客户端 -
var client = Promise.promisifyAll(client);
Run Code Online (Sandbox Code Playgroud)
现在,让我们用promises编写代码,.then
而不是用节点回调和聚合.map
.什么.then
是异步操作完成的信号..map
获取一系列内容并将它们全部映射到异步操作,就像您的hgetall调用一样.
请注意Bluebird如何Async
为promisifed方法添加(默认情况下)后缀.
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
});
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1112 次 |
最近记录: |