2017-09-01 84 views
1

我在一個小項目工作一個的getJSON調用異步的行爲,我想檢查流channelstatus使用的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元素來顯示它們的屬性。

+0

裏面'.forEach()'你更新'status'異步但在嘗試訪問它同步。不好..! – Redu

+0

這個老問題可能對你有幫助https://stackoverflow.com/questions/4878887/how-do-you-work-with-an-array-of-jquery-deferreds –

+0

作爲一個方面的說明不要使用用於迭代數組。相反,在這種情況下使用foreach。 – Deadron

回答

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) 
+0

感謝您的迴應!我會給這個鏡頭。一旦我發現頻道是'在線'還是'離線',我需要做的第二次$ .getJSON調用呢?這個調用具有不同的端點(如此不同的url)。我應該把它放在.then裏面的函數中嗎? –

+0

這應該在'.then()'裏面,因爲你想要從第一個響應中更新行爲 –