How are you making use of Promises, you need to chain a then
to access the value solved by the catch
to carry out the process of errors.
You can do something more or less like this:
// Note que estamos uma função assíncrona. Logo, todo valor que
// for retornado por ela será "encapsulado" por uma Promise.
async function getIp() {
const body = await fetch('https://httpbin.org/ip');
const data = await body.json();
// O valor retornado será algo como `Promise<object>`.
return data
}
getIp()
.then((resolvedJson) => {
console.log(resolvedJson.origin);
})
.catch((error) => {
console.error('Opa! Houve um erro:', error.message);
});
Another alternative is to make use of the async
/await
to consume another asynchronous function:
async function getIp() {
const body = await fetch('https://httpbin.org/ip');
const data = await body.json();
return data
}
async function main() {
try {
const resolvedJson = await getIp();
console.log(resolvedJson.origin);
} catch (error) {
console.error('Opa! Houve um erro:', error.message);
}
}
main();
It is also important to understand that to access the value of a function that returns a Promise
, should chain a then
or use it within an asynchronous function since, if this is not done, we will be interacting directly with the Promise
, and not with its solved value. An example of this behavior:
// A função abaixo retorna uma Promise que resolve após 500ms.
function getMessage() {
return new Promise((resolve) => {
setTimeout(() => resolve('Hello, world!'), 500);
});
}
// Tentando interagir diretamente:
console.log(getMessage());
// Interagindo usando `then` (o que aguarda a resolução da Promise:
getMessage()
.then((message) => console.log('Usando then:', message));
// Interagindo através de uma função assíncrona (o que aguarda a resolução da Promise:
async function main() {
console.log('Async/await:', await getMessage());
}
main();
Note:
It is always very important that you perform the proper error handling when using Promises. Be through the try
/catch
within an asynchronous function or the catch
chained in a function that returns a Promise
.
But it’s all right. You’re using
await
to capture the return ofapiIP
?– Andre