【问题标题】:Scope and Order AJAX Callbacks范围和顺序 AJAX 回调
【发布时间】:2017-05-02 18:00:13
【问题描述】:

此代码需要 1) 检查用户是否在线 2) 从稍微不同的 URL 获取他们的信息 3) 将两者都输出到 HTML。它有效,但不一致。在某些情况下,当运行用于输出 HTML 的函数时,它表示来自第一个请求(在线或不在线)的数据未定义。现在 streamData 和 userData 是全局变量。但我希望我能在没有它的情况下让它工作。让两个数据源同时在同一个地方始终可用时遇到问题。

  var getOnline = function(){
    for (var i = 0; i < twitchFaves.length; i++) {
      userName = twitchFaves[i];
      streamAjaxOnline(userName);
    }
  }
  var streamAjaxOnline = function(userName){
    $.ajax({
      type        : 'GET',
      url         :  "https://wind-bow.gomix.me/twitch-api/streams/" + userName,
      dataType    : 'jsonp',
      success     : function(twitchData) {

        streamData = twitchData;
        if (streamData.stream){
          userAjaxOnline(userName);
        }
      }
    });
  }
  var userAjaxOnline = function(userName){
    $.ajax({
      type        : 'GET',
      url         :  "https://wind-bow.gomix.me/twitch-api/users/" + userName,
      dataType    : 'jsonp',
      success     : function(twitchData) {
        userData = twitchData;
        displayTwitchOnline(streamData, userData);
      }
    });
  }

【问题讨论】:

  • 那个代码...不能工作。由于全局和异步逻辑,多次迭代将相互遍历。 for 循环不会等待异步逻辑完成。

标签: javascript jquery ajax asynchronous callback


【解决方案1】:

现在 streamData 和 userData 是全局变量

这真的很糟糕。这意味着对函数的多次调用将共享相同的变量并覆盖彼此的结果。

但我希望我能在没有它的情况下让它工作。

这相对容易:将数据传递给函数。一个非常简单的解决方案是:

var streamAjaxOnline = function(userName) {
  $.ajax({
    type: 'GET',
    url: "https://wind-bow.gomix.me/twitch-api/streams/" + userName,
    dataType: 'jsonp',
    success: function(twitchData) {
      if (streamData.stream) {
        userAjaxOnline(userName, streamData); // pass streamData here
      }
    }
  });
}
var userAjaxOnline = function(userName, streamData) { // accept streamData here
  $.ajax({
    type: 'GET',
    url: "https://wind-bow.gomix.me/twitch-api/users/" + userName,
    dataType: 'jsonp',
    success: function(twitchData) {
      // no need to store userData if you only use it here
      displayTwitchOnline(streamData, twitchData);
    }
  });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-13
    • 2011-10-13
    • 1970-01-01
    • 2011-11-11
    • 2014-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多