Martin AJ
Martin AJ

Reputation: 6697

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). Now I need to wait until both requests done. How can I determine an ajax request is done? If not wait until it get done?

Upvotes: 2

Views: 73

Answers (4)

Syed Arif Iqbal
Syed Arif Iqbal

Reputation: 1427

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

Upvotes: 2

Ken Wang
Ken Wang

Reputation: 1

this official document could help you.

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

Upvotes: 0

Suren Srapyan
Suren Srapyan

Reputation: 68655

Use Promise.all function. 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.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
});

Upvotes: 2

elclanrs
elclanrs

Reputation: 94101

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

Upvotes: 5

Related Questions