0

我正在尝试通过 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......等

我的代码有什么问题?是异步问题吗?我该如何解决?请帮我!谢谢

4

1 回答 1

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]); 

  }
});
于 2014-02-12T14:14:43.077 回答