🔹 What is a Promise?
A Promise in JavaScript is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
A Promise has 3 states:
- Pending – Initial state, neither fulfilled nor rejected.
- Fulfilled – The operation completed successfully.
- Rejected – The operation failed.
const promise = new Promise((resolve, reject) => {
// async operation
});
🔹 Basic Example
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const success = true;
if (success) {
resolve('Data fetched!');
} else {
reject('Error fetching data.');
}
}, 1000);
});
};
fetchData()
.then(data => console.log('Success:', data))
.catch(error => console.error('Error:', error));
🔹 Chaining Promises
const step1 = () => Promise.resolve('Step 1');
const step2 = prev => Promise.resolve(`${prev} → Step 2`);
const step3 = prev => Promise.resolve(`${prev} → Step 3`);
step1()
.then(step2)
.then(step3)
.then(result => console.log(result)); // "Step 1 → Step 2 → Step 3"
🔹 Error Handling in Chains
Promise.resolve('Start')
.then(() => {
throw new Error('Something went wrong');
})
.then(() => {
console.log('This will not run');
})
.catch(error => {
console.error('Caught error:', error.message);
});
🔹 Promise.all()
Runs multiple promises in parallel and waits for all to finish.
const p1 = Promise.resolve(1);
const p2 = Promise.resolve(2);
const p3 = Promise.resolve(3);
Promise.all([p1, p2, p3])
.then(values => {
console.log(values); // [1, 2, 3]
});
If any promise rejects, the whole Promise.all()
rejects.
🔹 Promise.race()
Returns the first settled promise (either fulfilled or rejected).
const p1 = new Promise(resolve => setTimeout(() => resolve('Fast'), 500));
const p2 = new Promise(resolve => setTimeout(() => resolve('Slow'), 1000));
Promise.race([p1, p2]).then(result => {
console.log(result); // "Fast"
});
🔹 Promise.allSettled()
Waits for all promises to settle, regardless of their outcome.
const p1 = Promise.resolve('Success');
const p2 = Promise.reject('Failure');
Promise.allSettled([p1, p2]).then(results => {
console.log(results);
});
Output:
[
{ status: 'fulfilled', value: 'Success' },
{ status: 'rejected', reason: 'Failure' }
]
🔹 Promise.any()
Returns the first fulfilled promise, ignores rejections.
const p1 = Promise.reject('Fail');
const p2 = Promise.resolve('Pass');
const p3 = Promise.resolve('Another Pass');
Promise.any([p1, p2, p3])
.then(result => console.log(result)); // "Pass"
If all promises reject, it throws an AggregateError.
🔹 Async/Await: Syntactic Sugar
const asyncFunc = async () => {
try {
const data = await fetchData();
console.log('Data:', data);
} catch (err) {
console.error('Error:', err);
}
};
✅ Under the hood, async
functions always return a promise.
🔹 Creating Delay with Promises
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
async function run() {
console.log('Wait for it...');
await delay(2000);
console.log('Done!');
}
run();
🔹 Common Pitfalls
1. Not returning in .then()
// WRONG
fetchData()
.then(data => {
doSomething(data);
// forgot to return
})
.then(more => console.log(more));
// CORRECT
fetchData()
.then(data => {
return doSomething(data); // chain continues properly
})
.then(more => console.log(more));
2. Using try/catch without await
// WRONG
try {
fetchData().then(data => console.log(data));
} catch (e) {
console.error('Will not catch error!');
}
🔹 Real-World Example: Fetch API
async function getUserData(userId) {
try {
const res = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
if (!res.ok) throw new Error('User not found');
const data = await res.json();
console.log(data);
} catch (error) {
console.error('Fetch error:', error);
}
}
getUserData(1);
Month | Savings |
---|---|
January | $250 |
February | $80 |
March | $420 |
Top comments (3)
sdfsd
new
sfd