Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to assign the returned value of a promise to a variable? [duplicate]

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.

like image 623
user305883 Avatar asked Sep 16 '15 15:09

user305883


1 Answers

You have to use the global variable trick, or accept use save-as-a-promise trick.

var getStuff = $.when(req1,req2).then(function(data1,data2) { return data1.concat(data2); });

//the variable getStuff is now a promise and any .then chained 
//to it will have data1.concat(data2) passed to it as an argument

getStuff
  .then(function(data1Data2) {
    console.log(data1Data2);
  });

//the next time you want to use it, you have to use the same promise-interface with .then
getStuff
  .then(function(data1Data2) {
    console.log(data1Data2);
  });
like image 194
Adam Avatar answered Oct 20 '22 19:10

Adam