0

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.

asportnoy
  • 2,218
  • 2
  • 17
  • 31
Ayush Yadav
  • 105
  • 3

2 Answers2

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

Giuk Kim
  • 170
  • 10
1

you can do it like this:

(async () => {
  let a = "";

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

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

  await abc();
  getA();
})();
ijavad
  • 176
  • 1
  • 8
  • thanks for your help too !!! but as i can only mark one of the answers correct so i'll do it for the one that came first :) – Ayush Yadav Apr 07 '23 at 04:49