What is a Promise - paulip114/blog GitHub Wiki
โ What is a Promise?
A Promise is a JavaScript object that represents the eventual result (or failure) of an asynchronous operation.
Think of it like a "contract" for a future valueโsomething that hasnโt happened yet, but will.
๐ง Analogy:
Imagine you order food online. You get a "promise" that it will arrive.
While you're waiting, you can keep doing other things.
Later, the food will either be:
- Delivered โ (fulfilled),
- Canceled โ (rejected), or
- Still on the way (pending...).
๐ฆ States of a Promise
A Promise has three states:
State | Meaning |
---|---|
pending |
The operation is still in progress |
fulfilled |
The operation completed successfully |
rejected |
The operation failed with an error |
โ๏ธ Syntax
const promise = new Promise((resolve, reject) => {
// async task
if (success) {
resolve(result); // fulfilled
} else {
reject(error); // rejected
}
});
๐ Handling Promises
promise
.then(result => {
// handle success
})
.catch(error => {
// handle error
});
setTimeout
๐ Example: Delay with function wait(ms) {
return new Promise(resolve => {
setTimeout(() => {
resolve("Done waiting");
}, ms);
});
}
wait(1000).then(msg => {
console.log(msg); // "Done waiting" after 1 second
});
โ Why use Promises?
- They make asynchronous code more manageable.
- Replace callback hell.
- Work well with
async/await
syntax.
async
/ await
(syntactic sugar for Promises)
๐ Bonus: async function example() {
const msg = await wait(1000);
console.log(msg);
}