I'm having trouble with some dumb architecture because I'm dumb. I'm trying to loop over YouTube videos posted to Reddit, extract URLs and process them into an .m3u playlist.
Full code at Subreddit to YouTube Source Bookmarklet - Play YouTube music from subreddits in Foobar with foo_youtube
At some point I get the idea that I could check each URL to see if the video is dead or not, and offer an alternative if they're removed.
So I do AJAX requests to YouTube API and if there's an error I'm supposed to react to it and change that item's URL.
But the problem is it only works if the AJAX is NOT async - this takes many seconds, during which the page is jammed.
I'd like to let the AJAX be async but I don't know how I should structure my code.
Here is PSEUDOCODE of how it is now:
var listing = // data from reddit API
$.each(listing, function(key, value) {
var url = // post URL from reddit posts listing
// ( "http://youtu.be/XmQR4_hDtpY&hd=1" )
var aRegex = // to parse YouTube URLs
// ( (?:youtube(?:-nocookie)?.com/....bla...bla )
var videoID = // YouTube video ID, extracted with regex
// ( "XmQR4_hDtpY" )
var itemArtist = // parsed from reddit posts listing
// ( "Awesome Artist" )
var itemTitle = // parsed from reddit posts listing
// ( "Cool Song (Original Mix)" )
var itemURL = // url, further processed
// ( "3dydfy://www.youtube.com/watch?v=XmQR4_hDtpY&hd=1" )
$.ajax({
type: "HEAD",
url: "https://gdata.youtube.com/feeds/api/videos/" + videoID,
error: function() {
// If it's no longer available
// (removed, deleted account, made private)
deadVid++; // chalk up another dead one, for showing progress
itemURL = // dead videos should get a different URL
// ( "3dydfy-search://q=Awesome%20Artist%20Cool%20Song....." )
}
});
// further process itemURL!
// at this point I want itemURL changed by the .ajax()'s error callback
// but I'm trying to keep the requests async
// to not jam the page while a hundred HTTP requests happen!
if (condition){
itemURL += // append various strings
}
// Write the item to the .m3u8 playlist
playlist += itemURL + '\n';
}// end .each()