我正在使用JavaScript YouTube API V3在某些视频数据中请求3个不同的播放列表。它成功地工作了,但是方法execute()
正在从循环中调用的顺序(刷新页面)中要求视频数据。该代码非常简单,可以在此处进行调试,或者在此处首选:
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);
}
我的理论是execute()
方法正在请求信息异步,但是如果这是正确的,我该怎么做才能在请求中设置订单?
您可以使用JavaScript承诺等待执行异步请求,并使用bluebird库从这篇文章中以正确的顺序循环:
var promiseFor = Promise.method(function(condition, action, value) {
if (!condition(value)) return value;
return action(value).then(promiseFor.bind(null, condition, action));
});
//Load and grant access to youtube api
function googleApiKey() {
var apiKey = 'YOUR_API_KEY';
gapi.client.setApiKey(apiKey);
gapi.client.load('youtube', 'v3', function() {
promiseFor(function(count) {
return count < playlists.length;
}, function(count) {
return requestVideo(playlists[count])
.then(function(response) {
//show video
for (var j = 0; j < response.items.length; j++) {
showVideo(response.items[j]);
}
return ++count;
}, function(error) {
console.log(response.error.message);
});
}, 0).then(console.log.bind(console, 'all done'));
});
}
function requestVideo(playlist) {
return new Promise(function(resolve, reject) {
var request = gapi.client.youtube.playlistItems.list({
part: 'snippet',
playlistId: playlist,
maxResults: 4
});
request.execute(function(response) {
if ('error' in response) {
reject(Error(response.error.message));
}
else {
resolve(response);
}
});
});
}
不要忘记添加蓝鸟链接
您可以在这里找到小提琴