2016-10-21 136 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