Get the value of a promise and assign to variable

前端 未结 3 1305
轮回少年
轮回少年 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: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
    

提交回复
热议问题