Get the value of a promise and assign to variable

前端 未结 3 1306
轮回少年
轮回少年 2021-02-04 14:04

utility.fetchInfo() returns a Promise object. I need to be able to get the value of this Promise object and assign the value of it to a variable that I can then use

相关标签:
3条回答
  • 2021-02-04 14:30

    What @dhilt said but do your stuff inside the promise callback function:

    utility.fetchInfo().then(result => { 
      doSomethingWith(result);
    });
    

    Or use async/await if you are using a recent version of Node or Babel:

    async function myFunction () {
        var myVal = await utility.fetchInfo();
    }
    
    0 讨论(0)
  • 2021-02-04 14:36

    When you return the value to another file/function and you are getting undefined because another function where you are using that value is not waiting for the value to be assigned to the variable. For example there are two function

    function1(){
       var x=desired_value
    }
    
    function2(){
       var y = x
    }
    

    now function1 might take some time to assign desire value to var x and java script ll not wait for this, it ll start running function2 and when you read the value of y you will get undefined.

    To solve this problem we can use java script promise/await/async, return value from async function as resolve. refer below example

    async function1(){  //function1 should be async here for this to work
       return new Promise(function(resolve,reject){
           resolve(desired_value)
    });
    }
    

    or above function can be writtern as

     async function1(){  //function1 should be async here for this to work
    
            return Promise.resolve(desired_value)
        }
    

    Now we can use this value in another function by calling the function1 and use await keyword

    function2(){
       var y = await function1();
    }
    

    now it ll wait for function1 to complete before assigning its value to y.

    0 讨论(0)
  • 2021-02-04 14:45

    Just do an assignment within the callback's body

    utility.fetchInfo().then(result => { myVal = result; });
    

    Depends on the situation, for example, if there's a big piece of async logic, it may be better to extract it in a separate function:

    let myVal; // undefined until myAsyncFunc is called
    
    const myAsyncFunc = (result) => { 
       console.log(result);
       myVal = result;
       // ...
    };
    
    utility.fetchInfo().then(myAsyncFunc); // async call of myAsyncFunc
    
    0 讨论(0)
提交回复
热议问题