AJAX return result using jQuery

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

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

Thanks!

+6
source share
1 answer

Finish always returns a promise, it makes no sense to return something from the function that you set to execute:

The deferred method .done () takes one or more arguments, all of which can be either a single function or a set of functions. When a Delayed Solution is resolved, doneCallbacks is called. Callbacks performed in the order in which they were added. Since a pending request () returns a pending object, other methods of the pending object can be riveted to this, including additional methods .done () Source: https://api.jquery.com/deferred.done/

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

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

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

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

 promise.then(function(data){ return $.ajax(...); }).done(function(resultFromAjaxCall){}); 
+3
source

All Articles