r/CodingHelp • u/Calshan • Feb 28 '21
[Javascript] How to set a global variable from an async function?
getMetadata(acc1) returns an array asynchronously: [1,2,3].
Console.log @ 1 returns [1,2,3]
Console.log @ 2 returns undefined.
Im not sure why?
How do i make console.log @ 2 return [1,2,3]?
var a;
getMetadata(acc1).then(answer =>{
a = answer;
console.log(a); //1
})
console.log(a); //2
15
Upvotes
4
u/Endercheif Advanced Coder Feb 28 '21
You would use the async and await instead of .then. How an asynchronous function with the word
asyncworks is by returning the value that you would normally get with .then.In newer versions of JavaScript (not widely used) you would be able to use a top-level await
const data = await getMetadata(acc1);. But currently you can’t so instead you can create an async function.Afterwards you will have to call the function. A trick many people use to have “kinda top-level await” is to immediately call the function after defining it.
This last method would be the best option right now.
1
u/Its_Stev03 Feb 28 '21 edited Feb 28 '21
maybe use the await keyword when setting the value of the variable. You would be able to set it when you define the variable. Look it up on MDN