-2
const url =
  "https://weather-by-api-ninjas.p.rapidapi.com/v1/weather?city=delhi";
const options = {
  method: "GET",
  headers: {
    "X-RapidAPI-Key": "ce580959b4msh04ac7f304c1ee24p143e88jsncf6cf022f1d6",
    "X-RapidAPI-Host": "weather-by-api-ninjas.p.rapidapi.com",
  },
};

try {
  const response  = await fetch(url, options);
  const result = await response.text();
  console.log(result);
} catch (error) {
  console.error(error);
}

I was try to fetch weather API from rapidAPI I just copyed the given code to fetch

MrUpsidown
  • 21,592
  • 15
  • 77
  • 131
  • Please [**search**](/search?q=%5Bjs%5D+await+is+only+valid+in+async) before posting. More about searching [here](/help/searching). – T.J. Crowder May 27 '23 at 12:34

1 Answers1

-2

This is because you are using await out of async scope.

Try to make the following change:

(async () => {
  try {
    const response  = await fetch(url, options);
    const result = await response.text();
    console.log(result);
  } catch (error) {
    console.error(error);
  }
})();
RAllen
  • 1,235
  • 1
  • 7
  • 10
  • 1
    I didn't downvote, but two possible reasons are: 1) This is a common duplicate 2) Async IIFE is kind of outdated. Use modules. – jabaa May 27 '23 at 12:36
  • 1) possibly 2) how can modules replace IIFE in the context above, where we need to check that `async` is a reason? – RAllen May 27 '23 at 12:41
  • You don't need Async IIFE in a module. Modules allow top-level await. You can use modules in modern (7 years old) browsers and most other engines. – jabaa May 27 '23 at 12:42
  • Right, but all of this has nothing to do with the snippet above, where we need to verify if `async` nature of context is a solution. I'm pretty sure that the code above (i.e. try-catch block) resides in some function too that can be made async (or the entire module will be async), but it is shown here without it for simplicity, and I used IIFE for simplicity too. – RAllen May 27 '23 at 12:46
  • 1
    If this is a code inside a function, and your answer is to wrap it in a async IIFE, I would also downvote. – jabaa May 27 '23 at 13:11