我正在尝试通过javascript制作谷歌缩短分析工具,这是我的代码:
<script>
function makeRequest() {
for (var i=0; i < shortUrl.length; i++){
var url = shortUrl[i];
var request = gapi.client.urlshortener.url.get({
'shortUrl': url,
'projection':'FULL',
});
request.execute(function(response) {
console.log(response); //here is the problem begin
var result = {
short: response.id,
clicks: response.analytics.allTime.shortUrlClicks
};
appendResults(result, i);
});
}
}
function load() {
gapi.client.setApiKey('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
gapi.client.load('urlshortener', 'v1', makeRequest);
}
</script>
<script src="https://apis.google.com/js/client.js?onload=load"></script>
每次结果都会让我与众不同! 例如: SHORTURL [1,2,3,4] 它将返回3,2,1,4或1,2,4,3 ......等等。
我的代码出了什么问题? 是异步问题?我该怎么办呢? 请帮我! THX
答案 0 :(得分:2)
因为ajax是异步的。你必须使用承诺。 jQuery示例。
var promises = [];
for (var i=0; i < shortUrl.length; i++){
var dfd = new $.Deferred;
var url = shortUrl[i];
var request = gapi.client.urlshortener.url.get({
'shortUrl': url,
'projection':'FULL',
});
request.execute((function(dfd){return function(response) {
dfd.resolve(response);
};})(dfd));
promises.push(dfd.promise());
}
$.when.apply($, promises).done(function(){
promises = undefined;
for(var i in arguments){
var response = arguments[i];
console.log(response); //here is the problem begin
var result = {
short: response.id,
clicks: response.analytics.allTime.shortUrlClicks
};
appendResults(result, i);
}
});
我的工作代码:
var promises = [];
var request = function(i, callback){
setTimeout(function(){return callback(i);},100 - i);
}
for (var i=0; i < 10; i++){
var dfd = new $.Deferred;
request(i, (function(dfd){return function(response) {
dfd.resolve(response);
};})(dfd));
promises.push(dfd.promise());
}
$.when.apply($, promises).done(function(){
promises = undefined;
for(var i in arguments){
console.log(arguments[i]);
}
});