Search code examples
javascriptjsonpromiserequestglobal-variables

How to pass a json array to a global variable


I want to pass the resulting promis array to a global variable. How can I do this? Unfortunately, I didn't understand from the documentation how to do this, but in the browser I can pass to a global variable and access the values by key. Unfortunately, the option with "foo().then(json => console.log(json))" is not suitable, because there is no initialization of the array. Thank you for any help! My code

async function foo(){
  var data = await fetch('http://127.0.0.1:8080/user'); 
  return data.json(); 
}

 let json = foo(); 
 console.log(json)

Solution

  • In your code you assign a Promise object to you variable json

    If you want to run asynchronous code, you need to pass a callback into the .then() method of Promise or wrap everything in async function and await for a result (see below).

    async function foo(){
      var data = await fetch('http://127.0.0.1:8080/user'); 
      return data.json(); 
    }
    
    const global;
    
    (async () => {
      const data = await foo();
      global = data;
      console.log('global', global)
    })()