ajax get before,ajax - jQuery .always() seems to fire before $.get() request is actually complete - ...

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!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值