Multiple AJAX calls in .each (), do something when everything is done, even if multiple errors

I am trying to check dead YouTube videos with HEAD requests to https://gdata.youtube.com/feeds/api/videos/<videoID>

. Now the whole point is that they are fast and that's it, but they won't work with 403 and 404:

HEAD https://gdata.youtube.com/feeds/api/videos/XmQR4_hDtpY 404 (Not Found)

and these errors seem to have messed things up.

I found Multiple ajax calls inside each function (), then do something when ALL are done? - Stack overflow and tried using this answer :

var videoIDs = ['a9KvHnHQVTc', 'XmQR4_hDtpY', 'WelBUaf5qsw', 'Mcrt9LJkGT4', 'P9qTLa2DVR8'];
var calls = [];
var deadVids = [];

$.each(videoIDs, function(index, value) {
    calls.push($.ajax({
        type: "HEAD",
        url: "https://gdata.youtube.com/feeds/api/videos/" + value,
        error: function() {
            deadVids.push('https://www.youtube.com/watch?v=' + value + " is dead!");
        }
    }));
});

$.when.apply($, calls).always(function(){
     console.log(deadVids.length);
   });

      

Since .then

it never registers deadVids.length

(= 4 ) in general, with .always

or .fail

it registers 1 after the first error.

How can I do something after all requests have completed, even if with errors?

(This code will eventually work as a bookmarklet, on reddit.com $.fn.jquery -> "2.1.1"

)


EDIT: This seems to explain why it only registers 1 :

  • If all pending requests are allowed, then issue callbacks done

    .
  • If one of the pending deviations is rejected, follow the callbacks fail

    .

via http://afgomez.es/blog/better-ajax-callbacks-with-jquery-promises/

EDIT 2: Using the global Ajax event handler .ajaxStop()

attached to document

writes 4 at the end of all AJAX requests

$( document ).ajaxStop(function() {
  console.log(deadVid);
});

      

EDIT 3 . It has been suggested to use .always (), but that won't work for me ... it will work after the first error. I was in Chrome 38 but when I tried Firefox 33 it works as expected, logs after all AJAX requests complete (1 OK and 4 fails, 4 logs). This is mistake?

0


source to share


1 answer


You only specify the succes function on the last call.

try



$.when.apply($, calls).then(function() {
        console.log(deadVid);
}, function(){
  //log failed
});

      

0


source







All Articles