javascript - How can I return once all child http requests complete in a parent http request -


i'm hitting api returns details on kills in game, first endpoint returns id kill event, second endpoint hit retrieve killer , killed names.

because of way api set need make request first event id , wait id's in returned array result , process entire kill array:

    requestify.get(url).then(function (response) {         var events = [];         if (response.body && response.body.length > 0) {             data = json.parse(response.body);             if (data.hasownproperty('events')) {                 events = data.events.map(function(event) {                     return this.getdataforherokillid(event.id, function(killinfo) {                         return { killer: killinfo.killer, killed: killinfo.killed, timestamp: event.time };                     });                 }.bind(this));                 console.log('events is: ', events);             }         }         return promise.all(events);     }.bind(this)); 

my getkillinformation function looks this:

killfeed.prototype.getkillinformation = function(id, cb) { var data = null;     requestify.get(url).then(function (response) {         var event = {};         if (response.body && response.body.length > 0) {             data = json.parse(response.body);             if (data.hasownproperty('killer')) {                 event = { killer: data.killer, killed: data.killed};             }         }         cb(event);     }); }; 

in second method hoping callback result of each child request , once had been executed new array hold data. due event driven nature of js found code block continues return empty events array code non blocking (understandably blocking event queue whilst making http request not ideal). how can implement this?

one uses promises this.

requestify.get(url).then(function (response) {     var events = [];      if (response.body && response.body.length > 0) {         var data = json.parse(response.body);         if (data.hasownproperty('events')) {             // trying process kill information here             events = data.events.map(function(event) {                 return this.getkillinformation(event.id).then(function(killinfo) {                     return { killer: killinfo.killer, killed: killinfo.killed, timestamp: event['time1'] };                 });             }.bind(this));         }     }      return promise.all(events); });  killfeed.prototype.getkillinformation = function(id) {     var url = 'internal_url';     return requestify.get(url).then(function (response) {         if (response.body && response.body.length > 0) {             var data = json.parse(response.body);             if (data.hasownproperty('killer')) {                 return { killer: data.killer, killed: data.killed };             }         }     }); }; 

Comments