What causes the 'await is only valid in async functions' error when calling a weather API with RapidAPI in JavaScript?

I encounter an error about await being valid only in async functions when fetching weather data. For example:

const urlEndpoint = "https://sampleweatherapi.com/info?city=Miami";
const requestOptions = {
  method: "GET",
  headers: { "X-API-KEY": "dummyapikey" }
};

function showWeather() {
  const response = await fetch(urlEndpoint, requestOptions);
  console.log(await response.json());
}

showWeather();

How can I resolve this issue?

hey, try prefixing the function with async. await only works inside async funcs so just change it to async function showWeather(){…} and it’ll sort itself. cheers

I encountered a similar problem while working on a project that required fetching data from an external API. For me, the error occurred because I was using await inside a normal function, which JavaScript doesn’t allow. I resolved this by converting the entire function into an asynchronous one, thereby permitting the use of await within its context. This allowed the asynchronous operation to handle its promise correctly and enabled proper error handling if the API call failed. My experience underscores the importance of ensuring that any function expecting asynchronous behavior is defined with async, to avoid such runtime issues.

hey, you gotta prefix your function with async. await won’t work in a regular func so adding async fixes it. hope this helps!

The error occurs because JavaScript enforces the use of await within an asynchronous context. In my own work on network-related features, I once encountered this problem when experimenting with nested function calls. I resolved it by wrapping the code in an immediately invoked async function, which allowed me to use await without issues. Alternatively, I ensured that any function using await was defined with the async keyword. This approach not only resolves the error but also ensures that the asynchronous behavior is properly managed and any potential errors can be caught using try-catch blocks.