我正在使用 youtube api 来检索视频列表的信息。所以我必须使用 Request.JSONP 类。
我的问题是我必须对 youtube API 进行多次调用,但我无法将其设为“链式”。文档说我只需要添加选项link:'chain'
并在同步模式下使用async:false
(女巫在简单的请求对象上工作正常)。
这是我尝试过的:
var MyClass = new Class({
listVideos: [],
videosInfo: [],
initialize : function(listVideos){
this.listVideos = listVideos;
this.getVideosInfo();
},
getVideosInfo : function(){
var request = new Request.JSONP({
callbackKey: 'callback',
link : 'chain',
async : false,
onComplete: function(data){
this.videosInfo.push(data.entry);
console.log(this.videosInfo);
}.bind(this)
});
this.listVideos.each(function(videoId){
request.options.url = 'http://gdata.youtube.com/feeds/api/videos/' + videoId + '?v=2&alt=json-in-script&format=5';
request.send();
});
console.log("this should be displayed AFTER the requests, not BEFORE u_u");
console.log(this.videosInfo);
}
});
var test = new MyClass(['AJso1SJT7Js','hlO5UBxuJlY'])
这是jsfiddle,所以你可以玩它 n_n
基本上我想要的是videosInfo
在所有请求完成后处理数组。
有任何想法吗?
提前致谢
PS: 我为我的问题找到了一个“肮脏的解决方案”,http://jsfiddle.net/pleasedontbelong/gLF5h/1/ 但如果其中一个请求失败,我一点也不觉得舒服......失败