Firstly I want to ask if this is possible or not,Setting value to global variable inside async function or promise?
If yes then why does every available tutorial/website uses console.log(results) in the tutorial but never uses it to assign it to variable.
For example:
var promise1 = new Promise(function(resolve, reject) {
resolve('foo');
});
let myval="";
promise1.then(function(value) {
myval=value;
console.log(value); // this logs "foo"
});
console.log(myval); //this logs blank
If you want to access the changed version of myval
(that is, execute your code after the assignment inside the Promise has been done), you need to either follow up with yet another then
, or do anything else that'd put your code in the event queue after the assignment.
var promise1 = new Promise(function(resolve, reject) {
resolve('foo');
});
let myval="a";
promise1.then(function(value) {
myval=value;
console.log(value); // this logs "foo"
});
setTimeout(() => console.log(myval), 0); // logs "foo"
var promise1 = new Promise(function(resolve, reject) {
resolve('foo');
});
let myval="a";
promise1.then(function(value) {
myval=value;
console.log(value); // this logs "foo"
}).then(function() {
console.log(myval) // logs "foo"
});
And an await example, probably the one you're looking for:
await
inside.then
promise into a variable (you can, obviously, omit that variable altogether and await
directly)await
that promise before your console.log
(async () => {
var promise1 = new Promise(function(resolve, reject) {
resolve('foo');
});
let myval="";
var thenedPromise = promise1.then(function(value) {
myval=value;
console.log(value); // this logs "foo"
});
await thenedPromise; // wait before the promise generated by "then" is resolved
console.log(myval); // logs "foo"
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With