Node.js & Redis & For Loop with bluebird Promises?

Node.js & Redis & For Loop with bluebird Promises?

我想要一个函数来创建一个看起来像这样的新 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() 更快。我如何正确使用 bluebird promises 和 redis,以便 return 值包含我想要的所有数据?

您只需从 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 + " }";
    })
}

请注意此函数是异步的,因为它 returns 一个最终将解析为字符串的 Promise。所以你这样称呼它:

makeThesenJSON.then(function (json) {
  //do something with json
})