This is likely a misunderstanding on my part of how AJAX functions, but I have a situation where a $.get callback (.always()) is being called before the GET request actually finishes. At least, that's what it looks like.
The Code
var apiRequest = 'some/url/';
// fetch list of video embed codes
$.get( apiRequest, function( embed_codes ) {
// added this per Explosion Pills' answer
var jqxhrs = [];
// for each embed code, get video details (name, duration, etc.)
for ( var i = 0; i < embed_codes.length; i++ ) {
var videoDetailsRequest = '/v2/assets/' + embed_codes[i];
//..declare vars..
// fetch video details
var jqxhr = $.get( videoDetailsRequest, function( video ) {
// build playlist entry for each video
playlistItem = '
' + video.name + '
' + video.description + '
';// create object of video HTML, with key = "video name" for sorting later
videoArray[video.name] = playlistItem;
}, 'jsonp' )
// added this per Explosion Pills' answer
jqxhrs.push( jqxhr );
}
// updated from jqxhr.always( function() {
$.when( jqxhrs ).always( function() {
// create array of keys
for ( k in videoArray ) {
if ( videoArray.hasOwnProperty( k ) ) { keys.push( k ); }
}
// append alphabetized list of videos to the page...
});
}, 'jsonp' );
What the Code Does
Essentially, the code does this: loop through a list of video embed codes. For each iteration of the for loop, fetch details about each video and push those details into a multidimensional array. Once done fetching all videos, call the .always() callback, which sorts the videos into an alphabetized playlist and appends to the page.
The Problem
The .always() callback sometimes gets called before all of the videos have been fetched. There are 9 videos in the playlist, but sometimes only 6 or 7 are returned before the callback is fired, which means my playlist is a bit short. I have tested this by alert()ing the number of keys and using the console. What I've seen is that 6-7 videos will return, then the alert() in the callback fires, then the remaining videos are returned.
MY QUESTION:
Why is this happening? I thought the .always() callback fired after the AJAX request was complete. Doesn't this mean that all of the videos should be returned before the callback is fired? I suspect it has to do with the "A" in AJAX, but I thought the purpose of the always() callback was to account for this. Anything to help me understand is greatly appreciated. Thanks!