Search code examples
javascriptpromiseasync-awaitfetch

How to structure this async function to get a synchronous response


Here's some example code I have:

async function getAppState() {
  return {
    appState: {
      someBar: false
    }
  },
  async function req() {
    const resp = await fetch("https://www.example.com/script.php", {
      method: 'GET',
    })
    this.appState.someBar = await resp.json();
  }
}
let foo = await getAppState();
console.log(foo)

I want to be able to get appState populated and pass it as an argument to console.log as in my example above. Clearly what I am doing does not work. I am attempting to show that I want to run getAppState() in a synchronous fashion so that I can get the result of the fetch() invocation into console.log after the function is invoked. What is the correct way to structure this code to do that?


Solution

  • getAppState() doesn't need to be asynchronous. It's just an object constructor, it doesn't perform the fetch() itself.

    You need to call the req() method with await to wait for the fetch().

    req also needs to be in the object that you're returning.

    function getAppState() {
      return {
        appState: {
          someBar: false
        },
        async req() {
          const resp = await fetch("https://www.example.com/script.php", {
            method: 'GET',
          })
          this.appState.someBar = await resp.json();
        }
      }
    }
    let foo = getAppState();
    await foo.req();
    console.log(foo.appState.someBar);