PurpleSmurph
PurpleSmurph

Reputation: 2107

$.ajax success function wait

Due to the (my perceived) nature of the $.ajax GET I'm not sure what I'm looking for is possible in this method, but thought I should ask as it's causing me some trouble. I am in no way an expert on JS, apologies if this is obvious, the title is poor, couldn't think of a different way to say it.

What I'm doing - using $.ajax to get values from the back-end API functions (these work). In the success property I'm using an anonymous function to pass more data across that would not otherwise be brought back. When stepping through the console breakpoints in the Chrome console the success function is often skipped as it's not brought back quick enough.

What I would like - in the example below, I don't want getStuff to complete, before its success DoSomething has returned, as I'm missing loads of data from the API which I need to pass through to DoSomething - is this possible to achieve?

Example

function getStuff(id, hid) {
    $.ajax({
        type: "GET",
        url: "/api/GetMyStuff/" + id,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (vData) {
            DoSomething(vData, id, hid); // not always being hit
        }
    });
}

Upvotes: 1

Views: 2863

Answers (2)

Holt
Holt

Reputation: 37606

You could use the async option and set it to false to get a synchronous call:

function getStuff(id, hid) {
    $.ajax({
        type: "GET",
        url: "/api/GetMyStuff/" + id,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: false, // HERE
        success: function (vData) {
            DoSomething(vData, id, hid); // not always being hit
        }
    });
}

But that is not a good way to do ajax request, you should rethink your code organization (like giving a callback function to your getStuff method and calling it in the success callback).

Upvotes: 3

jmar777
jmar777

Reputation: 39649

What you are trying to do is impossible. Asynchronicity is "leaky", meaning that any asynchronous action requiring a callback (e.g., $.ajax()) necessarily forces asynchronous control flow all the way up the call chain.

Please note that in the near future (thanks to async/await in ES7), this situation gets a little better. The asynchronicity is still leaky, but the new keywords make the refactoring scenario a little easier than hand-jamming callbacks everywhere.

Upvotes: 1

Related Questions