[英]How can I return once all child http requests complete in a parent http request
I'm hitting an API which returns all details on kills in a game, the first endpoint returns an id to the kill event, then a second endpoint is hit to retrieve the killer and killed names. 我正在点击一个API,它返回游戏中杀戮的所有细节,第一个端点返回一个id到kill事件,然后第二个端点被命中以检索杀手并杀死名字。
Because of the way this API is set up I need to make a request to first get the event ID and then wait for all id's in the returned array to get a result and then process the entire kill array: 由于这个API的设置方式,我需要首先获取事件ID,然后等待返回数组中的所有id获取结果,然后处理整个kill数组:
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 like this: 我的getKillInformation函数如下所示:
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 the second method I was hoping that I could callback the result of each child request and then once they had all been executed my new array would hold the data. 在第二种方法中,我希望我可以回调每个子请求的结果,然后一旦它们全部被执行,我的新数组将保存数据。 But due to the event driven nature of JS I found that my code block continues to return an empty events array as this code is obviously non blocking (understandably as blocking the event queue whilst making a HTTP request is not ideal). 但是由于JS的事件驱动特性,我发现我的代码块继续返回一个空事件数组,因为这个代码显然是非阻塞的(可以理解为阻塞事件队列,同时发出HTTP请求并不理想)。 How can I implement this? 我该如何实现呢?
One uses promises for 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 to process the 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 };
}
}
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.