Terry Chen
Terry Chen

Reputation: 427

Design to block asynchronous javascript

var flow;

$.ajax({
    url: "qa/version.json",
    dataType: "json",
    success: function( response ){ 
        flow = response.Version;
    }
});

$(".flow").append(flow);

Due to the nature of JS asynchronous design, the append would will be execute before it is being assigned a value in ajax call. What is the best way to tell the script to wait until flow gets assigned in ajax call, then do the append? I do not want to put append right below the success, I would like to keep them separate.

Upvotes: 0

Views: 67

Answers (4)

lshettyl
lshettyl

Reputation: 8171

Or:

var request = $.ajax({
    url: "qa/version.json",
    dataType: "json"
});

request.done(function(response){
    $(".flow").append(response.Version);
});

Upvotes: 0

Brad
Brad

Reputation: 163272

I have no idea why you don't want to put your success handler in the spot for a success handler, but here's an alternative that may help you.

jQuery returns a Deferred instance when you make AJAX requests. You can use its .done() method to set up a callback later.

var dfd = $.ajax( /* your code here, without the success handler */);

// later on...
dfd.done(function (response) {
  $('.flow').append(response.Version);
});

See also:

Upvotes: 0

David
David

Reputation: 218798

The "best way" is to perform the action in response to the asynchronous action:

$.ajax({
    url: "qa/version.json",
    dataType: "json",
    success: function(response){ 
        $(".flow").append(response.Version);
    }
});

If you want to "keep them separate" then you can define a function to call in the response:

var appendFlow = function (flow) {
    $(".flow").append(flow);
};

$.ajax({
    url: "qa/version.json",
    dataType: "json",
    success: function(response){ 
        appendFlow(response.Version);
    }
});

Separating the code into its own function is simply a matter of organizing your code into re-usable components. Either way, by design the response can't be processed until it's received, so you'd perform your actions in response to the asynchronous call.

Upvotes: 4

Erik Philips
Erik Philips

Reputation: 54618

Anything wrong with:

$.ajax({
  url: "qa/version.json",
  dataType: "json",
  success: function( response ){ 
    flow = response.Version;
    $(".flow").append(flow);
  }
});

Upvotes: 2

Related Questions