Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return AJAX promise's result with jQuery [duplicate]

Can someone explain why in the following example, foo() is returning the whole promise instead of just the data ? And how to make foo() return only the data ?

var foo = function() {
  var promise = $.ajax({
    type: 'POST',
    url: 'http://example.com'
  })

  return promise.done(function(data) {
    return data
  })
}

console.log(foo())

Thanks!

like image 589
inwpitrust Avatar asked Mar 28 '14 10:03

inwpitrust


1 Answers

Done always returns the promise, it does not make sense to return anything from the function that you supply to done:

The deferred.done() method accepts one or more arguments, all of which can be either a single function or an array of functions. When the Deferred is resolved, the doneCallbacks are called. Callbacks are executed in the order they were added. Since deferred.done() returns the deferred object, other methods of the deferred object can be chained to this one, including additional .done() methods Source: https://api.jquery.com/deferred.done/

promise.done(...).done(...) or promise.done(fn1, fn2) are equivalent.

You can use .then if you want to return a new promise with a new value for "data", i.e.:

promise.then(function(data1){
  return data1.result;
}).done(function(data2){
  //the value of data2 here will be data1.result 
});

A somewhat common use of then is to return a new promise, for example:

promise.then(function(data){
  return $.ajax(...);
}).done(function(resultFromAjaxCall){});
like image 109
Rui Avatar answered Sep 28 '22 05:09

Rui