Here are some approaches to work with asynchronous requests:
- Browser Promise object
- Q - A promise library for JavaScript
- A+ Promises.js
- jQuery deferred
- XMLHttpRequest API
- Using callback concept - As implementation in first answer
Example: jQuery deferred implementation to work with multiple requests
var App = App || {};App = { getDataFromServer: function(){ var self = this, deferred = $.Deferred(), requests = []; requests.push($.getJSON('request/ajax/url/1')); requests.push($.getJSON('request/ajax/url/2')); $.when.apply(jQuery, requests).done(function(xhrResponse) { return deferred.resolve(xhrResponse.result); }); return deferred; }, init: function(){ this.getDataFromServer().done(_.bind(function(resp1, resp2) { // Do the operations which you wanted to do when you // get a response from Ajax, for example, log response. }, this)); }};App.init();