Promises help you handle tasks that take time, like loading data, without freezing your program. They make your code easier to read and manage when working with things that happen later.
Promises for cleaner async in Node.js
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Node.js
new Promise((resolve, reject) => {
// Do some async work
if (success) {
resolve(result); // Task finished successfully
} else {
reject(error); // Task failed
}
});resolve is called when the task finishes well.
reject is called when something goes wrong.
Examples
Node.js
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Done!');
}, 1000);
});Node.js
myPromise.then(result => {
console.log(result);
}).catch(error => {
console.error(error);
});Node.js
fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
Sample Program
This program waits 1.5 seconds, prints a message, then waits 1 more second and prints another message. It uses promises to handle the waiting cleanly.
Node.js
function wait(ms) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(`Waited ${ms} milliseconds`);
}, ms);
});
}
wait(1500)
.then(message => {
console.log(message);
return wait(1000);
})
.then(message => {
console.log(message);
})
.catch(error => {
console.error('Error:', error);
});Important Notes
Promises let you chain tasks with .then() for better flow.
Always add .catch() to handle errors and avoid crashes.
Promises make your code easier to read compared to nested callbacks.
Summary
Promises help manage tasks that take time without freezing your program.
Use resolve and reject to signal success or failure.
Chain .then() and .catch() to handle results and errors cleanly.
Practice
1. What is the main purpose of using Promises in Node.js?
easy
Solution
Step 1: Understand asynchronous tasks
Asynchronous tasks take time and can block the program if not handled properly.Step 2: Role of Promises
Promises allow handling these tasks without freezing the program by running code after the task finishes.Final Answer:
To handle asynchronous tasks without freezing the program -> Option DQuick Check:
Promises manage async tasks = A [OK]
Hint: Promises help avoid freezing during slow tasks [OK]
Common Mistakes:
- Thinking Promises speed up code execution
- Confusing Promises with synchronous code
- Believing Promises store data permanently
2. Which of the following is the correct way to create a Promise in Node.js?
easy
Solution
Step 1: Check Promise constructor syntax
The Promise constructor requires a function with two parameters: resolve and reject.Step 2: Validate each option
const p = new Promise((resolve, reject) => { /* code */ }); correctly uses new Promise with a function taking resolve and reject.Final Answer:
const p = new Promise((resolve, reject) => { /* code */ }); -> Option BQuick Check:
Correct Promise syntax = B [OK]
Hint: Use 'new Promise' with (resolve, reject) function [OK]
Common Mistakes:
- Omitting 'new' keyword
- Passing resolve and reject outside a function
- Using incorrect Promise constructor syntax
3. What will the following code output?
const promise = new Promise((resolve) => {
setTimeout(() => resolve('Done'), 100);
});
promise.then(result => console.log(result));
console.log('Start');medium
Solution
Step 1: Understand asynchronous setTimeout
The setTimeout delays resolve by 100ms, so 'Done' logs after delay.Step 2: Order of console logs
'Start' logs immediately, then after 100ms 'Done' logs from the promise.Final Answer:
Start\nDone -> Option CQuick Check:
Async delay means 'Start' first, then 'Done' [OK]
Hint: Immediate logs appear before delayed Promise results [OK]
Common Mistakes:
- Assuming Promise resolves immediately
- Expecting 'Done' before 'Start'
- Ignoring asynchronous behavior of setTimeout
4. Identify the error in this Promise code:
const p = new Promise((resolve, reject) => {
resolve('Success');
reject('Error');
});
p.then(result => console.log(result))
.catch(error => console.log(error));medium
Solution
Step 1: Understand Promise state changes
Once a Promise is resolved or rejected, further calls to resolve or reject are ignored.Step 2: Analyze code behavior
The code calls resolve first, so reject after that does nothing.Final Answer:
Calling reject after resolve has no effect -> Option AQuick Check:
Promise settles once; later calls ignored [OK]
Hint: Promise settles once; ignore calls after resolve/reject [OK]
Common Mistakes:
- Expecting both resolve and reject to run
- Forgetting Promise settles only once
- Confusing order of resolve and reject calls
5. You want to run two async tasks one after another using Promises. Which code correctly chains them to run sequentially?
hard
Solution
Step 1: Understand sequential chaining
To run tasks one after another, call the second in the first's .then() callback.Step 2: Analyze options
task1().then(() => task2()).then(result => console.log(result)); chains task2 after task1 completes, ensuring order.Final Answer:
task1().then(() => task2()).then(result => console.log(result)); -> Option AQuick Check:
Chain with .then() for sequential async tasks [OK]
Hint: Use .then() chaining to run tasks one after another [OK]
Common Mistakes:
- Using Promise.all for sequential tasks (runs parallel)
- Calling tasks without chaining (runs parallel)
- Misusing catch to run second task
