1

I am working on a small project where I want to check the status of a streaming channel using an API and display that channels status and information if the status is online

Here's what I'm thinking

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
        });
    }
});

How can I make these async calls synchronous so that I can build the Channel objects in the channels array based on the responses of API calls? After I build the channels array I'm going to iterate through them to great new HTML elements to display their properties.

Quinn V.
  • 31
  • 3
  • Inside `.forEach()` you update the `status` async but trying to access it sync. No good..! – Redu Sep 01 '17 at 19:51
  • this old so question might be of help to you https://stackoverflow.com/questions/4878887/how-do-you-work-with-an-array-of-jquery-deferreds – Shyam Babu Sep 01 '17 at 19:58
  • As a side note do not use for in to iterate over Arrays. Use foreach in this scenario instead. – Deadron Sep 01 '17 at 20:09

1 Answers1

1

Your best bit is to use Promise.all. Here's a pseudo code (not a working one - just a sketch for you to implement) you can use

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

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

Promise.all(promises)
Nafiul Islam
  • 1,220
  • 8
  • 20
  • Thanks for the response! I will give this a shot. What about the second $.getJSON call i need to do once I find out if the channel is 'online' or 'offline'? This call has a different endpoint (so different url). Should i put it in the function inside of the .then? – Quinn V. Sep 01 '17 at 20:16
  • That should be inside `.then()` as you want to update behavior from first response – Nafiul Islam Sep 02 '17 at 03:40