# AJAX Calls within jQuery Loops

I have the following code, which is working (?), but I guess I can do it simpler and more elegantly. I need to invoke a method when everything is completed (channelsVideos array is filled). The console.log function at the end runs and display the array. The objects are in it, but it is displayed as Array[0] in the console. All I want is to be sure that all the data is donwloaded before creatign the UI elements.

menuItemsAndTabs: [],
categoriesAndChannels: [],
channelsVideos: [],

...
...
...

getChannelsAndVideos: function() {
$.each(MyApp.menuItemsAndTabs[1].menuItem.tabs, function(index, value) { var _id = value._id; var ajaxGetChannels =$.getJSON(MyApp.CONSTANTS.URLS.API + "/api/assets/" + _id, function(response) {

}).done(function(response) {
$.each(response.channels, function(ind, val) { MyApp.categoriesAndChannels.push({ channel: { categoryName: value.label, channelName: val.channelId, channelId: val._id } }); var ajaxGetVideos =$.getJSON(MyApp.CONSTANTS.URLS.API + "/videos/channel/" + val.channelId, function(response) {

}).done(function(response) {
\$.each(response.videos, function(ind, val) {
MyApp.channelsVideos.push({
channelName: val.channelId,
videos: {
title: val.title
}
});
});
});
});

});
});

console.log(MyApp.channelsVideos);

},

• Usually the best way to wait for multiple async operations is to use promises. Sep 15 '17 at 5:04