EDITED as comment to duplicate I quote from: [How do I return the response from an asynchronous call?
Promises are containers for future values. When the promise receives the value (it is resolved) or when it is cancelled (rejected), it notifies all of its "listeners" who want to access this value.
This question is about how to return the value contained in the promise. The answer was useful to me, because it clarified that it is not possible to return the value, rather to access the value within the promise function.
Other useful sources about the subject, here:
- How do I return the response from an asynchronous call?
- http://www.html5rocks.com/en/tutorials/es6/promises/
- jQuery deferreds and promises - .then() vs .done().
Below the original question:
Could you please help in understanding how to get the value from a promise and differences between these two examples ?
//I have a simple ajax call like:
var fetch = function(start_node, end_node) {
var apiEndpoint = 'localhost/nodes/';
var loadurl = apiEndpoint+start_node+'/'+end_node;
return $.ajax({
url: loadurl,
type: 'GET',
dataType: 'json',
jsonpCallback: 'json'
});
};
// Then I processed results in something like:
var getResult = function(data) {
// do smtg with data
var result = {'myobject' : result_from_data}
return result
}
And finally I want to assign it results.
The following works, but I think it wastes the concept of the promise since result is assigned to a global variable declared before it:
var r;
fetch('val1','val2')
.then(function(data){
r = getResult(data);
})
Instead the following assigns the promise function to res
.
var res = fetch('val1','val2')
.done(function(data){
return getResult(data);
})
Could you clarify how to pass the resulting 'myobject'
to the variable res
, and not the promise itself?
I also tried:
var res = $.when(fetch('val1','val2'))
.done(function(data){
return getResult(data);
})
but no success.