Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Attempting to call a API

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."

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

Use this code instead:

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'
    }
};
var result;
fetch(url, options)
.then((data) => {
    result = data.text();
    console.log(result);
})
.catch((error) => {
    console.error(error);
});
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'
    }
};
var result;
fetch(url, options)
.then((data) => {
    result = data.text();
    console.log(result);
})
.catch((error) => {
    console.error(error);
});

The await syntax is removed by using then to wait for the promise to resolve.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading