Javascript 如何等待两个ajax请求完成?

Javascript 如何等待两个ajax请求完成?,javascript,jquery,ajax,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] =

以下是我的代码的简化版本:

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请求是否完成?如果不等到它完成

你可以使用承诺:

Promise.all([
  $.ajax({ url: 'test1.php' }),
  $.ajax({ url: 'test2.php' })
])
.then(([res1, res2]) => {
  // Both requests resolved
})
.catch(error => {
  // Something went wrong
});
使用功能。如果解析了所有承诺并将数据作为数组传递给
然后
函数,则将解析该承诺,否则将使用第一个承诺失败值拒绝该承诺

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

您也可以使用回调函数

var res = [];

function addResults(data) {
    res.push(data);
    console.log('Request # '+res.length);
    if ( res.length >= 2 ) {
        // do stuff
        console.log('both request has done.');
    } else {
        // wait 
    }
}

$.ajax({
    url: 'https://jsonplaceholder.typicode.com/posts',
    success: function (data) {
        addResults(data);
    }
});

$.ajax({
    url: 'https://jsonplaceholder.typicode.com/posts',
    success: function (data) {
        addResults(data);
    }
});

这份官方文件可以帮助你

例如:

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

隐马尔可夫模型。。看起来不错,投票吧。你能告诉我这些承诺到底做了什么,我什么时候应该使用它们吗?@MartinAJ,这可能有用。承诺基本上是一个表示未来价值的对象,在本例中是一个响应<代码>承诺。所有并行运行承诺,
。然后
将在成功解决这两个问题时为您提供值。我明白了,谢谢。为什么不在ajax请求中编写
success
block?我应该写它们,对吗?
成功
错误
回调不再推荐,因为
$。ajax
返回承诺现在您可以在
然后
块中处理回调,如您所见。啊,我明白了,再次感谢您。如果您能以单独的语法编写代码,我将不胜感激。目前,您已经在
promise.all
中将ajax请求作为数组编写。你能把它们分开写,然后在《承诺》中使用吗?如您提供的示例中的第一个示例。我只是想完全理解承诺。顺便说一下,没有必要明确地说
async:true
。这是默认值。谢谢。向上投票。但是,我认为您需要将函数放入一个循环中。当前执行
else{//wait
块时会发生什么情况?在
res.length>=2
为真之前不需要再次调用它?