代码之家  ›  专栏  ›  技术社区  ›  snazzybouche

如何在转到下一个之前等待Ajax调用完成?

  •  1
  • snazzybouche  · 技术社区  · 8 年前

    listOfUrls

    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

    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
    

    for

    1 回复  |  直到 8 年前
        1
  •  2
  •   Rory McCrossan Hsm Sharique Hasan    8 年前

    成功完成前一个URL后,可以使用递归调用下一个URL。

    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