Bằn*_*aru 0 javascript ajax jquery promise
我需要迭代一个数组(或一个简单的 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);
});
}
Run Code Online (Sandbox Code Playgroud)
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");
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2155 次 |
| 最近记录: |