简体   繁体   English

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

[英]How can I wait until both ajax requests done?

Here is a simplified of my code: 这是我的代码的简化:

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 
}

As you can see I've used async: true to run those ajax requests at the same time (in parallel) . 正如您所看到的,我使用了async: true来同时运行这些ajax请求(并行) Now I need to wait until both requests done. 现在我需要等到两个请求完成。 How can I determine an ajax request is done? 如何确定ajax请求已完成? If not wait until it get done? 如果不等到它完成?

You can use promises: 你可以使用承诺:

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

You can use callback function as well. 您也可以使用回调函数。

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

Use Promise.all function. 使用Promise.all函数。 It will be resolved if all of the promises is resolved and pass the data as array to the then function, else it will be rejected with the first promise failure value 如果所有的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
});

this official document could help you. 这份官方文件可以帮到你。

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

example: 例:

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

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

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