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

标签 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" }] }

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/

相关文章:

redis - 使用不同的 Auth key 为 Redis 配置 HAproxy

javascript - 删除在 Jest 中记录原点行

node.js - 添加依赖项时 create-react-app 不起作用

language-agnostic - 循环终止条件

redis - 使用redis存储时间序列/历史数据

php - 有 Predis 文档吗?

node.js - 如何使用 NPM 打包部署?

javascript - Node.js/Express 错误 : cannot GET/

python - 具有多个变量的 For 循环 - Python

java - 计算数字中不重复的数字