I am currently utilizing an API that provides detailed information on kills in a game. The initial endpoint returns an ID for the kill event, followed by a second endpoint to retrieve the names of both the killer and the killed player.
Due to the structure of this API, I need to first request the event ID and then wait for all IDs in the returned array to fetch results before processing the 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));
The getKillInformation function is structured as follows:
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 my attempt with the second method, I intended to callback the result of each individual request, and once they had all been executed, the new array would hold the data. However, due to the asynchronous nature of JavaScript, my code block continues to return an empty events array. This non-blocking behavior is understandable, as blocking the event queue while making an HTTP request is not ideal. How can I address this issue?