Return in Promise

Asked

Viewed 168 times

1

Hello I have a function that brings the ip in httpbin, however it is a file and I can’t put the result in a Return, only when it runs with console.log another direct mode:

Funciana like this...

async function apiIP() {
              try {
                const resposta = await fetch("http://httpbin.org/ip")
                const dados = await resposta.json()

                console.log dados.origin
              } catch(e) {
                // statements
                console.log(e);
              }

    }

but it doesn’t work when I use Return...

async function apiIP() {
              try {
                const resposta = await fetch("http://httpbin.org/ip")
                const dados = await resposta.json()

                return dados.origin
              } catch(e) {
                // statements
                console.log(e);
              }

    }
  • 1

    But it’s all right. You’re using await to capture the return of apiIP?

1 answer

4

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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.