Home > Web Front-end > JS Tutorial > What is the difference between Promise Chaining and Aync/await

What is the difference between Promise Chaining and Aync/await

Linda Hamilton
Release: 2024-11-16 15:47:02
Original
339 people have browsed it

Qual a diferença de Encadeamento de Promises e Aync/await

Today I was faced with my own ignorance about the difference between these two ways of dealing with asynchronous operations, so I decided to read and research to write this post — as a reminder to myself and, Who knows, maybe help other developers to better understand this difference.

At the time, I more or less knew how to explain that they both do the same thing, with then() bringing the resolved data, while resolve and reject were used to end with success or error. Async/await had await to wait for the result before moving on to the next step. It wasn't completely wrong, but it could be explained in a much better way.

Promise

Promise, as the name suggests, is a data return "promise" that goes through three main states:

  1. Pending: Initial state, when the promise has not yet been resolved or rejected.
  2. Fulfilled: The operation was completed successfully.
  3. Rejected: The operation failed and the error was caught.
const minhaPromise = new Promise((resolve, reject) => {
  let sucesso = true; // Apenas um exemplo condicional

  if (sucesso) {
    resolve("Operação concluída com sucesso!");
  } else {
    reject("Ocorreu um erro na operação.");
  }
});
Copy after login

Promise Chaining

This was the most common way of dealing with Promises before async/await. We use the then(), catch() and finally() methods.

  • then(): Used to receive and manipulate the successfully resolved data.
  • catch(): Used to handle the error when the promise is rejected.
  • finally(): Used to execute code regardless of the result.
minhaPromise
  .then((mensagem) => {
    console.log(mensagem); // "Operação concluída com sucesso!"
  })
  .catch((erro) => {
    console.error(erro); // Se der erro, isso será executado.
  })
  .finally(() => {
    console.log("Finalizando a execução da Promise"); // Sempre será executado.
  });
Copy after login

Async/Await

A function marked async automatically returns a Promise, and await is used to "pause" execution until the Promise is resolved.

async function buscarDados() {
  try {
    const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
    const data = await response.json();
    console.log("Dados recebidos:", data);
  } catch (error) {
    console.error("Erro ao buscar dados:", error);
  }
}

buscarDados();
Copy after login

The Difference

Promises chaining can cause the code to become very nested, especially when we use several then() in a row, making reading more difficult.

Async/await allows you to write asynchronous code in a way that is more similar to synchronous code, making the logic easier to read and understand. The code becomes cleaner, especially when we need to handle multiple asynchronous operations.

In addition, the way to handle errors using try/catch with async/await is more intuitive than just using catch in Promises.

The above is the detailed content of What is the difference between Promise Chaining and Aync/await. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template