Arzan0 Arzan0 - 1 month ago 20
Node.js Question

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

i want a function that makes a new JSON Object that looks so :

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


This
{ text: "aaaaa", kat:"a" }
in thesenjsondata and this
T-ID_12
is an entry of the array Thesen_IDS. And my solution so far is :

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;
}


I know, that the for-loop is faster then the db.getAsync(). How can i use the bluebird promises with redis right, so that the return value has all data that i want ?

Answer

You just create an array of promises out of Redis calls, then use Bluebird's Promise.all to wait for all to come back as an array.

function makeThesenJSON(number_these, Thesen_IDS) {

  var promises = [];

  for (var i = 0; i < number_these; i++) {
    promises.push(db.getAsync(Thesen_IDS[i]))
  }

  return Promise.all(promises)
    .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 + " }";
    })
}

Note how this function itself is .thenable because it returns a Promise that will eventually resolve to a string. So you call it like this:

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