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, as the name suggests, is a data return "promise" that goes through three main states:
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."); } });
This was the most common way of dealing with Promises before async/await. We use the then(), catch() and finally() methods.
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. });
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();
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!