First of all, it is worth saying that its function is incorrect. The result of request
will never be returned by getJSON
, since the return
is inside the callback of function request
, and not of the getJSON
. In that case, how are you working with a callback, I think it’s more interesting to return a Promise
directly:
function getJSON() {
const options = {
url: 'https://economia.awesomeapi.com.br/json/all',
method: 'GET'
};
return new Promise((resolve, reject) => {
request(options, function(error, response, body) {
if (error) {
reject(error);
} else {
resolve(body);
}
});
});
}
const cota = getJSON()
.then((body) => {
console.log('Recebi o body:', body);
})
.catch((error) => {
console.error('Algo deu errado:', error);
});
Note that in the above example, async
was not necessary as the operator await
was not used at any time within the function getJSON
.
If you want to use asynchronous function, you can use the API fetch
- which is a native alternative to the library request
. Learn more here. Thus:
async function getJSON() {
const response = await fetch('https://economia.awesomeapi.com.br/json/all');
const body = await response.json();
return body();
}
const cota = getJSON()
.then((body) => {
console.log('Recebi o body:', body);
})
.catch((error) => {
console.error('Algo deu errado:', error);
});
Now, let’s go to error:
SyntaxError: await is only valid in async function
The operator await
can only be used within functions marked as async
, as the error message left - at least in my view - very clear.
Therefore, you cannot use the await
out of asynchronous functions, which makes the following snippet of your code invalid:
var cota = await getJSON();
// ↑↑↑↑↑
// INVÁLIDO, como está FORA de uma função marcada com o `async`
So you have two options:
- Use the
then
, since every asynchronous function returns a Promise
. I did this example above. Or:
- Use another asynchronous function. Something like this:
async function getJSON() {
const response = await fetch('https://economia.awesomeapi.com.br/json/all');
const body = await response.json();
return body();
}
(async () => {
try {
const body = await getJSON();
console.log('Recebi o body:', body);
} catch (error) {
console.error('Algo deu errado:', error);
}
})();
In the above case, I used an asynchronous IIFE.