Summary - Promises
- Node.js course
- Beginner
- Lesson 93/116
- 5 min
Combine then, Promise.all and finally to write a parallel downloader.
Summary - Promises
In this group you learned the basics of Promises. A Promise represents the future result of an async operation and has three states: pending, fulfilled and rejected. To get the result you use then, to catch errors catch, and for cleanup finally.
For parallel work, Promise.all returns a result array when all finish; Promise.race gives the result of the first to finish. These are the core tools for managing several async jobs in a single flow. In the next lesson we will write the same logic more readably with async/await.
Practice Your turn: build a chain
Start with Promise.resolve(5). Use .then(n => n * 2) to double the value. Add .then(n => console.log(n)) to log it. Finally add .finally(() => console.log("done")).
Starter code
// Start with Promise.resolve
// Multiply with .then, log with .then, add .finallySample solution
Promise.resolve(5)
.then(n => n * 2)
.then(n => console.log(n))
.finally(() => console.log("done"));Expected output
10 done
Practice Your turn: race with Promise.race
Create const a = new Promise(res => setTimeout(() => res("first"), 10)) and const b = new Promise(res => setTimeout(() => res("second"), 30)). Call Promise.race([a, b]) and log the winner with .then(winner => console.log(winner)).
Starter code
// Create a and b Promises
// Use Promise.race to log the winnerSample solution
const a = new Promise(res => setTimeout(() => res("first"), 10));
const b = new Promise(res => setTimeout(() => res("second"), 30));
Promise.race([a, b]).then(winner => console.log(winner));Expected output
first
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does a finally call not change in a Promise chain?
- The error state of the chain
- The speed of the async work
- The order of the chain
- The previous Promise's value Correct answer
Explanation: finally only causes side effects; it keeps the value.
2 Match the Promise methods
| Term | Meaning |
|---|---|
then |
runs on success |
catch |
catches errors |
finally |
runs always |
Promise.all |
resolves when all done |