【问题标题】:How to wait for an ajax call to finish before moving on to the next?如何在继续下一个之前等待 ajax 调用完成?
【发布时间】:2018-06-12 23:53:23
【问题描述】:

我遇到需要发出多个 ajax 请求的情况。我需要访问的 URL 作为字符串包含在 listOfUrls 数组中。

我想做的是发出一个 ajax 请求,对其进行处理,将数据反馈到我的应用程序中,然后转到下一个。

我现在得到的代码的基本版本是这样的

var fetch = function(url) {
  $.get(url, function(response) {
    // do stuff with the data
  };
  return someData;
};

for(let i = 0; i < listOfUrls.length; i++) {
  fetch(listOfUrls[i]);
  console.log("Fetching " + listOfUrls);
};

// do more stuff after all requests are finished

这里的问题是这些是异步请求,虽然我可能只使用同步请求,但我真的不想冒险 - 然后我将无法在循环中使用 console.log,因为浏览器会挂起。

我更喜欢使用 promise 来遍历循环:

var fetch = function(url) {
  $.get(url, function(response) {
    // do stuff with the data
  };
  return someData;
};

for(let i = 0; i < listOfUrls.length; i++) {
  fetch(listOfUrls[i]).done( /* move onto the next one */ ).fail( /* throw an error */ );
  console.log("Fetching " + listOfUrls);
};

// do more stuff after all requests are finished

Promise 显然不能强制通过 for 循环进行迭代。

我将如何实现这种行为?

【问题讨论】:

    标签: jquery ajax promise


    【解决方案1】:

    您可以在成功完成前一个 URL 时使用递归调用下一个 URL。

    如果我希望 fetch() 也将数据返回到调用它的脚本部分,我该怎么做?

    由于所有请求都是异步的,因此您无法返回任何内容。要执行您需要的操作,您可以使用从所有请求中检索到的数据填充一个数组,然后将其提供给您在所有请求完成后调用的另一个函数,如下所示:

    var obj = [];
    
    function makeRequest(index) {
      $.get(listOfUrls[index || 0], function(response) {
        // do stuff with the response
        obj.push(response);
    
        if (++index < listOfUrls.length) {
          makeRequest(index);
        } else {
          finaliseRequests(obj);
        }
      });
    }
    
    function finaliseRequests(data) {
      // work with all the received data here...
    }
    
    makeRequest(); // onload
    

    【讨论】:

    • 如果我希望 fetch() 也将数据返回到调用它的脚本部分,我该怎么做?在您的示例中,我会将数据返回到它之前的 fetch() 中,这不是我想要的。我已更新我的问题以解决此问题
    • 这似乎是一个合理的解决方案。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-06
    • 1970-01-01
    • 2021-05-25
    • 2011-02-15
    • 2015-09-16
    • 2020-02-24
    • 2017-10-23
    相关资源
    最近更新 更多