Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set value of global variable inside async function or inside promise? [duplicate]

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
like image 856
Prabhjot Singh Kainth Avatar asked Dec 25 '19 10:12

Prabhjot Singh Kainth


1 Answers

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:

  • wrap everything into an immediately invoked async function, so we can use await inside
  • save the .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"
})();
like image 92
John Smith Avatar answered Oct 16 '22 17:10

John Smith