Skip to content

Promises

A Promise is an object representing an asynchronous operation (that takes time) and its future result.
It can be in three states:

  • pending → waiting (the promise has not settled yet)
  • fulfilled → successfully resolved (resolve)
  • rejected → failed (reject)

➡ Instead of blocking the code, a Promise allows you to wait for the result later.


let promise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Success");
} else {
reject("Error");
}
});
promise
.then(result => console.log(result)) // on success
.catch(error => console.error(error)) // on error
.finally(() => console.log("Promise settled")); // always executed

function wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
wait(1000).then(() => console.log("1 second passed"));

function getUser() {
return new Promise((resolve, reject) => {
setTimeout(() => {
let success = true;
if (success) {
resolve({ name: "Alice", age: 25 });
} else {
reject("Unable to fetch user");
}
}, 2000);
});
}
getUser()
.then(user => console.log("User:", user))
.catch(err => console.error("Error:", err));

  • Always handle errors with .catch() (or with try/catch if using async/await).
  • Use .finally() to run code regardless of outcome (success or error).
  • Prefer async/await for more readable and maintainable code when chaining promises.