Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access value of a global variable that got updated in a async function in javascript

well i am new to JavaScript and am trying to update a global variable inside an async function then i call another function (i.e., after the async function is called) to access the global variable but somehow the global variable isn’t updated.

to better explain the problem, see this code.

let a = "";

async function abc() {
   a = "hello";
}

function getA() {
   console.log(a);
}

abc();
getA();

However, when I call it, the value of a remains unchanged

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

basically in my code i am trying to read a small text from a file and then save it in a variable after which i use another function to process that text and get output.

Please help !!

Earlier i was using the async function to return the text instead of updating the global variable in that case some sort of promise used to come up and when i tried to console.log() it was fine it said promise fulfilled but when i used to access it. It said undefined.

>Solution :

there is two option.

let a

function sleep(ms){
  return new Promise((r) => {
    setTimeout(r, ms)
  })
}

async function abc() {
  await sleep(100)
  a = 'hello'
}

function getA() {
  console.log(a)
}

async function main(){
    await abc()
    getA()
}
main()
console.log('~~~')

or

    let a

    function sleep(ms){
      return new Promise((r) => {
        setTimeout(r, ms)
      })
    }

    async function abc() {
      await sleep(100)
      a = 'hello'
    }

    function getA() {
      console.log(a)
    }
    
    abc().then(()=>getA())
    console.log('~~~')

first option is wait until a is set.
second option is uses promise..

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading