I have the following code that gets the JSON from an array of YouTube video ids. It works great when all the videos exists and the query is successful. It sends several getJSON request, and when all of them are done... the $.when.done() fires and I can process the resulting data.
var
results = {},
promises = [];
$(document).ready(function() {
var
vids = [
'ozj2-bnTL3s',
'EAZ4Tlt8MQ4',
'Xn9o7cxqVoA'
// ,'this-videoid-doesnot-exists'
],
url = 'http://gdata.youtube.com/feeds/api/videos/{{vid}}?v=2&alt=json';
$.each(vids, function(idx, vid){
var
u = url.replace('{{vid}}', vids[idx]),
p = null;
p = $.getJSON( u ).done(function(data) {
results[vid] = data.entry;
});
promises.push(p);
});
$.when.apply($, promises).done(function(){
console.log(results);
});
});
But... In the final app I don't control if all the videos still exists in YouTube, I've realized that sometimes one (or several) of the videos in the list may have been deleted... or the id that I get from the DB is incorrect.
Is there any way that I could safely add to the results variable only the videos that where successful whiteout trigger the $.when.fail()? and waiting that all the queries had finished...
I mean, my final goal is to get the data from the videos that exist (those that its data was successfully retrieved), and, somehow to ignore those that don't exist or where unavailable... and I don't figure right now how to do it.
Any idea / approach will be appretiated. TIA!
You can find the code in this JSFiddle