user892134
user892134

Reputation: 3224

Execute code after multiple $.get calls have finished

How can I execute some code when both these $.get calls have completed?

if (invoice.is(":checked")) {
    var data = {
        save: 1,
        order_id: order_id
    }

    jQuery.get('http://domain.co.uk/customer_orders/edit/view_pdf', data, function(response) {});
}

var receipt = $(this).parents(".admin_email_preview_container").find("input[name='receipt']");
if (receipt.is(":checked")) {
    var data = {
        save: 1,
        order_id: order_id,
        invoice: 1
    }

    jQuery.get('http://domain.co.uk/customer_orders/edit/view_pdf', data, function(response) {});
}

I want to run another $.get call only after the above two calls are finished. How can I solve this?

Upvotes: 0

Views: 68

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

You can store the promises returned by $.get in an array and apply that to $.when(). Try this:

var requests = [];

if ($invoice.is(":checked")) {
    requests.push($.get('http://domain.co.uk/customer_orders/edit/view_pdf', {
        save: 1,
        order_id: order_id
    }));
}

var $receipt = $(this).parents(".admin_email_preview_container").find("input[name='receipt']");
if ($receipt.is(":checked")) {
    requests.push($.get('http://domain.co.uk/customer_orders/edit/view_pdf', {
        save: 1,
        order_id: order_id,
        invoice: 1
    }));
}

$.when.apply(requests).done(function() {
    // both $.get calls have completed, run other code here...
    $.get('/other-endpoint');
});

Note that I tidied your code slightly by the consistent use of $ instead of jQuery (if you need to prevent contamination of the $ variable, use a closure), I moved the objects directly in to the $.get calls to make it easier to read and also removed the redundant empty callback functions.

Upvotes: 1

Related Questions