Reputation: 13
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 ?
Upvotes: 0
Views: 344
Reputation: 17486
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) {
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 + " }";
})
}
Note how this function is Async 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
})
Upvotes: 2