我正在使用javascript youtube API v3在一些视频数据中请求3个不同的播放列表。它成功运行,但方法execute()
正在请求循环中调用的顺序中的视频数据(刷新page)。代码非常简单,可以调试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);
}
我的理论是execute()
方法请求信息异步,但如果这是正确的,我该怎么做才能在请求中设置顺序?
答案 0 :(得分:1)
您可以使用Javascript Promise等待执行异步请求,并使用Bluebird库按照post的正确顺序循环它们:
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);
}
});
});
}
不要忘记添加bluebird link
你可以找到一个小提琴here