我有一些异步ajax请求
$.ajax({
url: 'first.php',
async: true,
success: function (data) {
//do stuff
}
});
$.ajax({
url: 'second.php',
async: true,
success: function (data) {
//do stuff
}
});
...
$.ajax({
url: 'nth.php',
async: true,
success: function (data) {
//do stuff
}
});
我想在每个请求完成时运行 console.log()
。
我通常这样写代码:
$.ajax({
url: 'first.php',
async: true,
success: function (data) {
$.ajax({
url: 'second.php',
async: true,
success: function (data) {
//till the last ajax
}
});
}
});
但是有人建议 Promise.all([])
。
如果我必须运行,比方说,4 个 ajax 请求,哪种方法最好/最快?
最佳答案
使用 Promise.all()
。
var promises = [];
promises.push(new Promise(done=>{
$.ajax({
url: 'first.php',
async: true,
success: done
});
}));
promises.push(new Promise(done=>{
$.ajax({
url: 'second.php',
async: true,
success: done
});
}));
promises.push(new Promise(done=>{
$.ajax({
url: 'nth.php',
async: true,
success: done
});
}));
Promise.all(promises).then(()=>{
console.log("All ajax completed.");
});
关于javascript - 如何等到多个ajax请求完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63689302/