Node.js& Redis&对于蓝鸟承诺的循环?

时间:2016-10-21 19:35:39

标签: node.js for-loop redis promise bluebird

我想要一个能够生成看起来如此的新JSON对象的函数:

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

thisnjsondata中的{ 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()更快。我怎样才能将redbird promises与redis一起使用,以便返回值包含我想要的所有数据?

1 个答案:

答案 0 :(得分:2)

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