【发布时间】:2013-12-05 10:42:35
【问题描述】:
过去一个小时一直在努力解决这个问题,似乎无法弄清楚:
app.get('/bk/domains/get', function (req, res) {
client.keys('*', function (e, d) {
d.forEach(function (data) {
client.hgetall(data, function (e, d) {
res.json({'host': data, 'config': d});
});
});
});
});
这是示例输出:
{
"host": "test.com",
"config": {
"url": "http://test.com/test.html",
"token": "source",
"account": "test",
"source": "google"
}
}
现在,由于 res.json,它在从 client.hgetall 吐出第一个值后立即死亡。我想在这个 json 响应中添加大约 10 个其他值,但似乎无法使其正常工作。我该怎么做?
我试过这个:
app.get('/bk/domains/get', function (req, res) {
var arr = [];
client.keys('*', function (e, d) {
d.forEach(function (data) {
client.hgetall(data, function (e, d) {
arr.push({'host': data, 'config': d});
});
});
});
});
但arr 始终为空。我还尝试将 arr 移到 app.get 之外,因为它可能是命名空间,但这也不起作用。
如何将 hgetall 中的 10 个值推送到单个数组中并将其作为 json 返回?
提前谢谢你!
【问题讨论】:
-
hgetall方法是异步的,只有get()方法完成后才会加入arr
-
checkout 这个答案,你需要等待所有的 arr.push 方法都不会被调用stackoverflow.com/questions/11275999/…
标签: javascript json node.js express