What is a Promise and what are its states?
Show answer — try answering out loud first
A Promise is an object that represents the future result of an asynchronous operation. It has three states: pending, fulfilled (resolved successfully), and rejected (failed with an error). They are handled with .then(), .catch(), and .finally().
A promise is like a voucher for a value that isn't ready yet. When you start an asynchronous task, it returns a promise that will be:
- pending: the task hasn't finished yet.
- fulfilled: it finished successfully and has a value (accessed with
.then()). - rejected: it failed and has an error (caught with
.catch()).
Once it goes from pending to fulfilled or rejected, it never changes again. Promises can be chained with .then(), and each .then() returns a new promise.
// Create a promise
const promesa = new Promise((resolve, reject) => {
const exito = true;
if (exito) {
resolve("¡Datos listos!"); // moves to fulfilled
} else {
reject("Algo falló"); // moves to rejected
}
});
// Consume it
promesa
.then((resultado) => console.log(resultado)) // "¡Datos listos!"
.catch((error) => console.log(error))
.finally(() => console.log("Terminado (con éxito o no)"));
// Chain promises: each then returns a new promise
Promise.resolve(2)
.then((n) => n * 2) // 4
.then((n) => n + 1) // 5
.then((n) => console.log(n)); // 5
// Run several in parallel
Promise.all([Promise.resolve(1), Promise.resolve(2)])
.then((resultados) => console.log(resultados)); // [1, 2]
- Forgetting the
.catch()and leaving errors unhandled. - Not returning inside a
.then()when chaining: if you don't return the value (or the next promise), the following.then()receivesundefined. - Thinking that
.then()runs immediately; it's actually asynchronous and runs after the synchronous code.
"A Promise represents the future result of an asynchronous operation. It has three states: pending while the task is running, fulfilled if it finishes successfully, and rejected if it fails. I handle success with
.then(), errors with.catch(), and whatever must always run with.finally(). I can chain them because each.then()returns a new promise, and to run several at once I usePromise.all. The key thing is to always handle errors with.catch()."
What does this print?
Promise.resolve(10)
.then((n) => n + 5)
.then((n) => console.log(n));
See answer
It prints 15. The first .then() receives 10, adds 5, and returns 15, which is passed to the second .then().