【问题标题】:Javascript - Iterate an array and call Jquery Ajax requests and wait for a request finished before moving to next request?Javascript - 迭代数组并调用 Jquery Ajax 请求并等待请求完成,然后再移动到下一个请求?
【发布时间】:2019-05-08 03:24:24
【问题描述】:

我需要迭代一个数组(或一个简单的 for 循环)来向服务器运行 Ajax 请求。问题是,要运行下一个元素,当前的 Ajax 请求必须先完成。

到目前为止,我已经尝试过这样但它不起作用,因为它似乎在移动到下一个请求之前没有等待 1 个 Ajax 请求完成。我认为 promise 和 then 可以做到,但事实并非如此。

var ajax = function(rasqlQuery) {

return new Promise(function(resolve, reject) {
    var getURL = "http://test" + "?username=rasguest&password=rasguest&query=" + encodeURIComponent(rasqlQuery);
                  $.ajax({
                    url: getURL,
                   // Not using async: false here as the request can take long time
                    type: 'GET',
                    cache: false,
                    timeout: 30000,
                    error: function(error) {
                        alert("error " + error.statusText);
                    },
                    success: function(result) { 
                        resolve(result) ;
                    }
                });   
});

}

var promise;

for (var i = 0; i < 10; i++) {
    // It should send Ajax request and wait the request finished before running to next iteration. 
    // Or if not possible, it can register 10 requests but they must be run sequentially.
    promise = ajax("select 1 + " + i).then(function(result) { 
        console.log("i: " + i);
        console.log("Result: " + result);
    });
}

【问题讨论】:

标签: javascript jquery ajax promise


【解决方案1】:

Promise 是一个异步操作,因此您需要将它们链接在一起,而不是在循环中发出它,也就是说下一次提取应该只发生在 (.then) 前一次完成之后:

var promise = Promise.resolve();

for (var i = 0; i < 10; i++) {
  // You need to use this IIFE wrapper or ES2015+ let otherwise printed `i`
  // will always be 10 because interaction between async behavior and closures
  (function (i) {
    promise = promise.then(function () {
      return ajax("select 1 + " + i).then(function(result) {
        console.log("i: " + i);
        console.log("Result: " + result);
      })
    })
  })(i);
}

promise.then(function () {
  console.log("all done");
})

【讨论】:

  • 谢谢,这正是我所需要的(console.log(i) 很适合关闭)。主要部分是 promise 将按顺序运行。
猜你喜欢
  • 1970-01-01
  • 2019-02-11
  • 2017-06-09
  • 2017-03-07
  • 2016-07-03
  • 1970-01-01
  • 2020-07-22
  • 2018-12-10
  • 2016-04-13
相关资源
最近更新 更多