我怎么能等到两个ajax请求完成?

时间:2017-09-16 05:19:04

标签: javascript jquery ajax

以下是我的代码的简化:

var res = array();

$.ajax({
    url: 'test1.php',
    async: true,
    success: function (data) {
        res[1] = data.result;
    }
});

$.ajax({
    url: 'test2.php',
    async: true,
    success: function (data) {
        res[2] = data.result;
    }
});

if ( /* both ajax request are done */ ) {
    // do stuff
} else {
    // wait 
}

正如您所看到的,我已经使用async: true同时运行这些ajax请求(并行)。现在我需要等到两个请求完成。如何确定ajax请求已完成?如果不等到它完成?

4 个答案:

答案 0 :(得分:5)

您可以使用承诺:

Promise.all([
  $.ajax({ url: 'test1.php' }),
  $.ajax({ url: 'test2.php' })
])
.then(([res1, res2]) => {
  // Both requests resolved
})
.catch(error => {
  // Something went wrong
});

答案 1 :(得分:3)

您也可以使用回调功能。

{{1}}

答案 2 :(得分:2)

使用 Promise.all 功能。如果所有的promise都被解析并将数据作为数组传递给then函数,它将被解析,否则它将被第一个promise失败值拒绝

Promise.all([
  $.ajax({ url: 'test1.php'}),
  $.ajax({ url: 'test2.php'})
])
.then(results => {
  // results is an array which contains each promise's resolved value in the call
})
.catch(error => {
   // The value of the first rejected promise
});

答案 3 :(得分:0)

这份官方文件可以帮到你。

http://api.jquery.com/ajaxStop/

示例:

var res = [];
$.ajax({
    url: 'test1.php',
    async: true,
    success: function (data) {
        res.push('Ajax one is complete');
    }
});

$.ajax({
    url: 'test2.php',
    async: true,
    success: function (data) {
        res.push('Ajax two is complete');
    }
});
var resALL = function(){
    console.log(this)
}
//After the requests all complete 
$(document).ajaxStop(resALL.bind(res))
相关问题