2016-10-21 45 views
0

我想要的功能,使一个新的JSON对象,看起来如此:Node.js&Redis&For循环与蓝鸟承诺?

{ T-ID_12 : [{ text: "aaaaa", kat:"a" }], T-ID_15 : [{ text: "b", kat:"ab" }], T-ID_16 : [{ text: "b", kat:"ab" }] } 

{ text: "aaaaa", kat:"a" }在thesenjsondata这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权限的蓝鸟承诺,以便返回值具有我想要的所有数据?

回答

2

您只需在Redis调用中创建一个承诺数组,然后使用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 
}) 
+0

函数的返回,现在是{ “isFulfilled”:假 “isRejected”:假 } – Arzan0

+0

见我如何使用这个功能 –

+0

THX编辑,它的工作,但我不得不“var thesenjsondata = JSON.parse(res);”更改为“var thesenjsondata = res;” – Arzan0