ok so i am creating a web app and i have run into some issues
first i make a request to an api endpoint this returns a json response i take what i need and ad it into a key value array
i then have to loop through all the items in this array and for each item i need to make a request to a second api endpoint that returns some html
i need to then append this html to an eliment on the page
i need this to be done one after another the issue i have is that the .each() loop finishes instantly while the requests are still on going in the background meaning the aliments are appended to the html eliment on the page way after they should
how can i make the loop wait untill the requests are done and html is appended before moving onto the next item in the array
$("#middlebox").fadeTo(3000, 0, function() {
$("#middlebox").html(LOADING);
});
$("#middlebox").fadeTo(3000, 1, function() {
var API_URL = window.location.href 'api.php?action=channels&category=' $this.data("text") '&username=' $("#username").val() '&password=' $("#password").val();
var CHANNELS = {};
var API_CHANNELS = '<div >';
$.getJSON(API_URL).done( function( API_RESULT ) {
$.each( API_RESULT.items, function( API_INDEX, API_ITEM ) {
var API_ID = API_ITEM.stream_id;
var API_ICON = API_ITEM.stream_icon;
CHANNELS[API_ID] = API_ICON;
});
}).then( function() {
$.each( CHANNELS, function( CHANNEL_KEY, CHANNEL_VALUE ) {
var EPG_URL = window.location.href 'api.php?action=epg&id=' CHANNEL_KEY '&username=' $("#username").val() '&password=' $("#password").val();
API_CHANNELS = '<div ><div ><img src="' CHANNEL_VALUE '" ></div>';
$.ajax({
url:EPG_URL,
type: 'GET',
dataType: 'html',
success:function(content,code) {
API_CHANNELS = content;
}
});
API_CHANNELS = '</div>';
});
$("#middlebox").fadeTo(3000, 0, function() {
API_CHANNELS = '</div>';
$("#middlebox").html(API_CHANNELS);
$("#middlebox").fadeTo(3000, 1, function() {
});
});
});
});
CodePudding user response:
Ajax calls are asynchronous so you can't use a synchronous loop to process the requests.
You can use Promise.all
to wait for all ajax requests and then process replies in a loop.
Promise.all(CHANNELS.map(function( CHANNEL_KEY, CHANNEL_VALUE ) {
var EPG_URL = window.location.href 'api.php?action=epg&id=' CHANNEL_KEY '&username=' $("#username").val() '&password=' $("#password").val();
return $.ajax({
URL: EPG_URL,
type: 'GET',
dataType: 'html'
}).then(function(content) {
return [CHANNEL_KEY, CHANNEL_VALUE, content];
});
})).then(function(channels) {
$.each(channels, function(CHANNEL_KEY, CHANNEL_VALUE, content) {
API_CHANNELS = '<div ><div ><img src="' CHANNEL_VALUE '" ></div>';
API_CHANNELS = content;
API_CHANNELS = '</div>';
});
$("#middlebox").fadeTo(3000, 0, function() {
/* ... */
});
});