我在一個小項目工作一個的getJSON調用異步的行爲,我想檢查流channel
的status
使用的API,並顯示該頻道的狀態和信息如果狀態online
如何解決在for循環
下面是我在想什麼
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
});
}
});
我怎樣才能讓這些異步調用同步,這樣我可以建立channels
數組中的Channel
對象基於API調用的迴應?在我構建channels
數組後,我將遍歷它們以獲得偉大的新HTML元素來顯示它們的屬性。
裏面'.forEach()'你更新'status'異步但在嘗試訪問它同步。不好..! – Redu
這個老問題可能對你有幫助https://stackoverflow.com/questions/4878887/how-do-you-work-with-an-array-of-jquery-deferreds –
作爲一個方面的說明不要使用用於迭代數組。相反,在這種情況下使用foreach。 – Deadron