oceansmoving
oceansmoving

Reputation: 165

Chained jQuery AJAX with promise

I am currently working on a project where 4 get requests are fired simultaneously. I am at the same time using fade effects, and the asynchronous nature of this results in empty data intermittently.

I have been looking into this method as described in Prefer way of doing multiple dependent ajax synchronous call to replace how I am currently doing

$.get('ajax_call_1').then(function(value) {
    return $.get('ajax_call_2');
}).then(function(result) {
    // success with both here
}, function(err) {
    // error with one of them here
});

But, my question is: How can I access the return from each request individually with the above?

Upvotes: 0

Views: 162

Answers (1)

Fabian Lauer
Fabian Lauer

Reputation: 9897

You've said the requests are sent simultaneously. The way you've written your code, they are sent sequentially though. Instead, with Promise.all, you can wait for all of the requests' promises and you'll be given an array with the results:

Promise.all([
    $.get('ajax_call_1'),
    $.get('ajax_call_2'),
    $.get('ajax_call_3'),
    $.get('ajax_call_4')
]).then(function(results) {
    var first = results[0];
    var second = results[1];
    ...
}).catch(function(err) {
    // called if one of the requests fails
});

Upvotes: 1

Related Questions