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 getJ
In a purely javascript Promise implementation (or a specialised library like Q or another), you could do this:
function getVideo(id) {
return new Promise(function(resolve, reject) {
var request = new XMLHttpRequest();
request.open('GET', 'url = 'http://gdata.youtube.com/feeds/api/videos/' + id + '?v=2&alt=json');
request.onload = function() {
if (request.status == 200) {
resolve(request.response); //we get the data here. So, resolve the Promise
} else {
reject(Error(request.statusText)); //if status is not 200 OK, reject.
}
};
request.onerror = function() {
reject(Error("Error fetching data.")); //error occurred, reject the Promise
};
request.send(); //send the request
});
}
function fetchVideos() {
var vids = [
'ozj2-bnTL3s',
'EAZ4Tlt8MQ4',
'Xn9o7cxqVoA'
// ,'this-videoid-doesnot-exists'
]
var promises = [];
for (var i in vids) {
promises.push(getVideo(vids[i]));
}
Promise.all(promises).then(function(dataArr) {
dataArr.forEach(function(data) {
console.log(data.entry);
});
}).catch(function(err){
console.log(err);
});
}