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
there is two option.
or
first option is wait until a is set.
second option is uses promise..
you can do it like this: