I'm using the javascript youtube API v3 to request 3 different playlists within some videos data. It's successfully working, but the method execute()
is requesting the video data out of the order that was called in the looping (refresh the page). The code is pretty simple and can be debugged here, or if preferred here:
var playlistsID = [...]
for (var i = 0; i < playlistsID.length; i++) {
function playlistItem() {
var request = gapi.client.youtube.playlistItems.list({
part: 'snippet',
playlistId: playlistsID[i],
maxResults: 4
});
request.execute(function(response) {
if ('error' in response) {
console.log(response.error.message);
}
else {
for (var j = 0; j < response.items.length; j++) {
showVideo(response.items[j]);
}
}
});
}
}
function showVideo(response) {
var videoThumb = response.snippet.thumbnails.medium.url,
container = document.getElementById("video-container"),
videoDiv = document.createElement("div"),
image = document.createElement("img");
image.setAttribute("src", videoThumb);
container.appendChild(videoDiv);
videoDiv.appendChild(image);
}
My theory is that the execute()
method is requesting the informations async, but if this is correct, What should I do to set a order in the requests?