Promises
Handle asynchronous operations with Promises — then, catch, chaining
Free tier: read the explanation here. Upgrade to Pro for Drills, Speed challenges & Mastery badges.
UpgradeKnowledge Debt detected
You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.
Explanation
A represents an asynchronous operation that will complete in the future — either with a value (resolved) or an error (rejected).
Three states: pending → fulfilled | rejected
const p = new Promise((resolve, reject) => {
setTimeout(() => resolve('done!'), 1000);
});
p.then(value => console.log(value)); // 'done!' after 1sChaining with .then():
javascript fetch('/api/user') .then(res => res.json()) .then(data => console.log(data.name)) .catch(err => console.error(err));
Each .then() returns a new Promise, enabling .
Promise.all — wait for multiple promises in parallel: ``javascript const [user, posts] = await Promise.all([ fetch('/api/user').then(r => r.json()), fetch('/api/posts').then(r => r.json()), ]);
Promise.allSettled — like Promise.all but doesn't reject if any fail. Returns array of {status, value/reason}.
Creating resolved/rejected promises:
javascript Promise.resolve(42) // immediately resolved Promise.reject(new Error('oops')) // immediately rejected
Examples
Basic promise chain
Promises can be chained — each .then returns a new promise
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
delay(500)
.then(() => { console.log('500ms passed'); return delay(500); })
.then(() => console.log('1000ms total passed'));Error handling with .catch
.catch handles any rejection in the chain; .finally always runs
fetch('https://bad-url.invalid/data')
.then(res => res.json())
.catch(err => {
console.error('Request failed:', err.message);
})
.finally(() => {
console.log('Always runs — cleanup here');
});How well did you understand this?
Next in JavaScript Core
async / await