how to assign the returned value of a promise to a variable?

46,099

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);
  });
Share:
46,099
user305883
Author by

user305883

I had PM experience in international development, advising for digital transformation policy. Left international aid sector to co-found my company, providing knowledge discovery services for brainstorming and insights. I led product and vision for 5 years. My interest in design thinking and prototyping moved me to get the hands dirty in coding. I removed the dust from partially completed degree in Computational Engineering, data structures and such, and thanks to stack-overflow I was hand down on python, software architecture, and MOOC courses in deep learning and data-science. http://nifty.works , http://genomics.nifty.works , http://food.nifty.works are my web platforms prototypes to search for connections in between of multiple entities. I played with tech stacks: noSQL dbs, neo4j, redis, elasticsearch, python flask, pandas, celery, prophet, a bit of tensorflow and numpy vectorisation for neural nets. As working activities, I do like to engage audiences in sci-tech, to encourage and motivate team, and as well to invest time in learning about the fundamentals for prototyping and exploring. I have the ideas over on imagining and prototyping, and appreciate working opportunities that rewards with benefits of continuous learning and brainstorming over areas that triggers the ideas! I m much inquisitive on network science and self-organisation models.

Updated on July 05, 2022

Comments

  • user305883
    user305883 almost 2 years

    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:

    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.

  • user305883
    user305883 over 8 years
    Thank you! So the only way it to use the variable inside the promise itself.
  • user305883
    user305883 over 8 years
    Thank you! So it is possible to access the value of the promise, only inside the promise itself. A little further: @Adam, I run the getStuff .then(function(data1Data2) { console.log(data1Data2); }); in the browser console, and it returns both the value and the promise itself. (e.g.: ` Object {'myobject' : result_from_data}, Object {}` Could you explain why?
  • Adam
    Adam over 8 years
    It doesn't return both the value and the promise itself - that statement returns the promise (which the browser console logs) and it also console.log's the data which is why you see two logs. Your two options are, as you said - use a global variable, or simply store the promise and always access it's data via a .then
  • agm1984
    agm1984 almost 7 years
    I do it like this: 1) Put your code inside a function that returns a promise, promiseFunction() 2) create an async function and put this inside: const varName = await promiseFunction().then((done) => { return done; }).catch((err) => { throw new Error(`RADICAL ERROR: ${err}`); });