skip to Main Content

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

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.

2

Answers


  1. 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..

    Login or Signup to reply.
  2. you can do it like this:

    (async () => {
      let a = "";
    
      async function abc() {
        a = "hello";
      }
    
      function getA() {
        console.log(a);
      }
    
      await abc();
      getA();
    })();
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search