如何修复for循环中getJSON调用的异步行为

时间:2017-09-01 19:40:36

标签: javascript jquery asynchronous foreach getjson

我正在开展一个小型项目,我希望使用API​​检查流媒体status的{​​{1}},并在状态为channel时显示该频道的状态和信息

这就是我的想法

online

如何使这些异步调用同步,以便我可以根据API调用的响应在const channelNames = ['channel1', 'channel2']; var channels = []; function Channel(name, status) { this.name = name; this.status = status; } //build the channels array of Channels for(var name in channelNames) { channels.push(new Channel(channelNames[name], null)); } channels.forEach(function(channel) { // call the API to get the status $.getJSON(url, function(data) { // in here update the status to 'online' or 'offline' depending on // the response from the API }); //Add additional properties to the object if the status is now 'online' if(channel.status === 'online') { $.getJSON(differentUrl, function(data) { // in here add more properties to the object depending on the // response from the API }); } }); 数组中构建Channel个对象?在构建channels数组之后,我将迭代它们到伟大的新HTML元素以显示它们的属性。

1 个答案:

答案 0 :(得分:1)

最好的一点是使用Promise.all。这是一个伪代码(不是一个工作的代码 - 只是一个草图供你实现),你可以使用

let channelNames = [a lot of ids here];
let promises = [];

while (channelNames.length > 0) {
    promises.push($getJSON(url).then(function() {}))
}

Promise.all(promises)