Promises
What is a Promise?
Section titled “What is a Promise?”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.
Creating a Promise
Section titled “Creating a Promise”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
Example with setTimeout
Section titled “Example with setTimeout”function wait(ms) { return new Promise(resolve => setTimeout(resolve, ms));}
wait(1000).then(() => console.log("1 second passed"));
Concrete example: simulated request
Section titled “Concrete example: simulated request”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));
Best practices
Section titled “Best practices”- Always handle errors with
.catch()
(or withtry/catch
if usingasync/await
). - Use
.finally()
to run code regardless of outcome (success or error). - Prefer
async/await
for more readable and maintainable code when chaining promises.