Quantcast
Channel: How do I return the response from an asynchronous call? - Stack Overflow
Viewing all articles
Browse latest Browse all 46

Answer by Mohan Dere for How do I return the response from an asynchronous call?

$
0
0

Here are some approaches to work with asynchronous requests:

  1. Browser Promise object
  2. Q - A promise library for JavaScript
  3. A+ Promises.js
  4. jQuery deferred
  5. XMLHttpRequest API
  6. 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();

Viewing all articles
Browse latest Browse all 46

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>