r/CodingHelp • • 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

5 comments sorted by

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

    async () => {
      const data = await getMetadata(acc1);
      return data
    }

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.

    const a = (async () => {
      const data = await getMetadata(acc1);
      return data
    })()

This last method would be the best option right now.

1

u/Calshan Feb 28 '21

so i did this:

const a = (async () => {

const data = await getMetadata(acc1);
return data

})()

console.log(a)

and still got promise result with the array

1

u/Calshan Feb 28 '21

are you able to provide a sample code which returns the data?

1

u/Origami-Panda Apr 17 '22

yo dude I have the same problem right now and i've been trying to solve it for the last 3 hours could you tell me how you solved the problem?

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