Level: Intermediate | Players: 14 callbacks and timers
Learning Objectives
- Know the three states of Promise (pending, fulfilled, rejected).
- You can create a Promise directly with
new Promise. - Process the results as
then,catch, andfinally. - Chaining can flatten the callback hell.
- Know the difference between
Promise.allandPromise.race.
1. What is a Promise?
A Promise is “a box that holds the result of an operation to be completed at some point in the future.” There are three states:
- pending: not finished yet
- fulfilled: success, has value
- rejected: failure, there is a reason (error)
const p = new Promise((resolve, reject) => {
setTimeout(() => resolve(42), 100);
});
If you call resolve, it will be fulfilled, and if you call reject, it will be rejected. Once the status is set, it cannot be changed.
2. then / catch / finally
p.then((value) => console.log(value))
.catch((err) => console.error(err))
.finally(() => console.log("end"));
The value returned from the callback of then goes into the next argument of then. If an error occurs, nearby catch catches it.
3. Chaining
If we rewrite the callback hell example as a Promise , it becomes flat.
step("1").then(() => step("2")).then(() => step("3"));
If a Promise is returned within then, the next then will wait until it completes.
4. Promise.all / Promise.race
Promise.all([p1, p2, ...]): All must succeed to succeed, if even one fails, it fails. The result is an array.Promise.race([p1, p2, ...]): Adopt the result determined first (success/failure).Promise.allSettled: Wait until everything is finished and return each status object array.
Core example
| file | Contents covered |
|---|---|
| 01_new_promise.js | Create your own with new Promise |
| 02_then_catch.js | Using then/catch/finally |
| 03_chaining.js | Sequential execution with chaining |
| 04_all_race.js | Promise.all / Promise.race |
⚠️ Common Mistakes
thendoes not return a value, so undefined is received in the nextthen.- Unhandled rejection occurs when used without
catch. - Forgetting that if even one of
Promise.allfails, it is a total failure. - I do not know that errors thrown within
new Promiseare automatically rejected. - Thinking that a Promise is “lazy” without knowing that it is executed immediately.
❓ Frequently Asked Questions (FAQ)
Q1. Can resolve/reject be called immediately? A. Yes. Still, the then callback runs asynchronously.
Q2. Difference between catch and then's second argument? A. onRej of then(onFul, onRej) does not catch errors thrown by onFul of the same then. catch is safer.
Q3. What if you return a Promise within a Promise? A. It is automatically resolved and then the value is passed to the next step.