繁体   English   中英

Javascript-迭代数组并调用Jquery Ajax请求并等待请求完成,然后再移至下一个请求?

[英]Javascript - Iterate an array and call Jquery Ajax requests and wait for a request finished before moving to next request?

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

到目前为止,我已经尝试过这种方法,但是它似乎无法等待1个Ajax请求完成,然后再移至下一个请求。 我以为那时的 诺言可以做到,但事实并非如此。

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

Promise是一个异步操作,因此您无需将它们链接在一起,而是需要将它们链接在一起,方法是说下一个访.then仅应在( .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");
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM