Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guaranteeing asynchronous request callback order in Javascript

In Javascript, I have two asychronous requests for data:

$.getJSON('http://foo.com', fooQuery, fooSuccess(data));
$.getJSON('http://bar.com', barQuery, barSuccess(data));

and two callbacks to process the received data:

fooSuccess(data) { // Stuff }
barSuccess(data) { // More Stuff }

How do I ensure barSuccess is executed only after fooSuccess completes?

Notes:

  • I want to keep the data requests as they are: asynchronous and non-blocking (since server responses may take a while).
  • But, I want the callbacks that process the data to be executed sequentially. That is, I do not want to execute barSuccess until fooSuccess completes.

Thanks so much for your wisdom and help!

like image 334
Chris Han Avatar asked Dec 28 '12 00:12

Chris Han


1 Answers

Here is how you would do it using the jQuery deferred object that is returned by ajax requests.

var fooDfd = $.getJSON('http://foo.com', fooQuery);
var barDfd = $.getJSON('http://bar.com', barQuery);

fooDfd.then(function(fooData){
    fooSuccess(fooData);
    barDfd.then(barSuccess);
});

like image 100
david Avatar answered Sep 28 '22 17:09

david