1

I am using a code example I found using fetch, async, await. I am having trouble figuring out how to substitute a .then in the code for another await.

Here is the code

    async function getData(url = "", data = {}) {
  // Default options are marked with *
  const response = await fetch(url, {
    method: "GET", // *GET, POST, PUT, DELETE, etc.
    headers: {
      "Content-Type": "application/json",
    },
  });
  return response.json(); // parses JSON response into native JavaScript objects
}

const response = getData(
  "https://site.api.espn.com/apis/site/v2/sports/football/nfl/scoreboard"
).then((data) => {
  console.log(data.leagues[0].name);
});

I tried

const response =  await getData(
  "https://site.api.espn.com/apis/site/v2/sports/football/nfl/scoreboard"
)

But got an error await is only valid in async functions and the top level bodies of modules

What should I do?

Aaron
  • 4,380
  • 19
  • 85
  • 141
  • Please show more context. Where/how are you running this code? Where in your application is the `getData()` called? – Bergi May 11 '23 at 17:47
  • https://stackoverflow.com/questions/69089471/async-await-syntaxerror-await-is-only-valid-in-async-functions-and-the-top-le – epascarello May 11 '23 at 18:41

1 Answers1

-2

The answer is on the description. Await is only allowed on an async function. what you can do is transform it on an function:

async function runGetData(){
    const response =  await getData("https://site.api.espn.com/apis/site/v2/sports/football/nfl/scoreboard")
    console.log(response)
}

runGetData()

If i just want to call runGetData without waiting for his response i can. Of couse i would not know when it was done executing without await or then.

Maxwell s.c
  • 1,583
  • 15
  • 29