I currently am running into the issue when I put in the API link for it to be run. Once I go to the console it states it is a await valid in async functions
From what I’ve attempted. I’ve tried to use the common fetch function. I’ve tried to made some adjustments to move over the code on the top of the lines. Error still continues.
const url = 'https://moviesdatabase.p.rapidapi.com/titles/search/keyword/%7Bkeyword%7D';
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': '3065ca2efamsh5511818a494e23fp1cbb2cjsna2ae6a53946f',
'X-RapidAPI-Host': 'moviesdatabase.p.rapidapi.com'
}
};
try {
let response = await fetch(url, options);
const result = await response.text();
console.log(result);
} catch (error) {
console.error(error);
}
As soon as I run the console. I get the message: "SyntaxError: await is only valid in async functions, async generators and modules."
It does appear to be an error on the const result but I am unfamiliar to what I need to do to fix the error.
3
Answers
await
keyword only use when you have aasync
function.Use this code instead:
The await syntax is removed by using then to wait for the promise to resolve.
Using top-level
await
is only possible when inside of a module.Kannu’s answer is on the right path, but you need to call the function or write it as an IIFE: