我想要一个函数来创建一个看起来像这样的新 JSON 对象:
{ T-ID_12 : [{ text: "aaaaa", kat:"a" }], T-ID_15 : [{ text: "b", kat:"ab" }], T-ID_16 : [{ text: "b", kat:"ab" }] }
thesenjsondata 中的 { text: "aaaaa", kat:"a"}
和 T-ID_12
是数组 Thesen_IDS 的一个条目。到目前为止,我的解决方案是:
function makeThesenJSON(number_these, Thesen_IDS){
var thesenjsondata;
var thesenids_with_jsondata = "";
for (i = 0; i < number_these; i++ ){
db.getAsync(Thesen_IDS[i]).then(function(res) {
if(res){
thesenjsondata = JSON.parse(res);
thesenids_with_jsondata += (Thesen_IDS[i] + ' : [ ' + thesenjsondata + " ], ");
}
});
}
var Response = "{ " + thesenids_with_jsondata + " }" ;
return Response;
}
我知道,for 循环比 db.getAsync() 更快。我如何正确使用带有 redis 的 bluebird promises,以便返回值包含我想要的所有数据?
最佳答案
您只需从 Redis 调用中创建一个 promise 数组,然后使用 Bluebird 的 Promise.all
等待所有内容作为一个数组返回。
function makeThesenJSON(number_these, Thesen_IDS) {
return Promise.all(number_these.map(function (n) {
return db.GetAsync(Thesen_IDS[n]);
}))
.then(function(arrayOfResults) {
var thesenids_with_jsondata = "";
for (i = 0; i < arrayOfResults.length; i++) {
var res = arrayOfResults[i];
var thesenjsondata = JSON.parse(res);
thesenids_with_jsondata += (Thesen_IDS[i] + ' : [ ' + thesenjsondata + " ], ");
}
return "{ " + thesenids_with_jsondata + " }";
})
}
请注意此函数是异步的,因为它返回一个最终将解析为字符串的 Promise。所以你可以这样调用它:
makeThesenJSON.then(function (json) {
//do something with json
})
关于Node.js & Redis & For Loop with bluebird Promises?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40184264/