Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the value of a promise and assign to variable

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 later on in my code.

At the moment, I can happily print the value of result to the console, but I need to be able to assign this value to myVal. So far, I've tried a lot of things and nothing has worked.

var myVal = utility.fetchInfo().then(result => console.log(result));

Thanks

like image 881
user2402135 Avatar asked Sep 22 '17 01:09

user2402135


1 Answers

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
like image 84
dhilt Avatar answered Sep 19 '22 10:09

dhilt