MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Promise Chaining0%
Study Materials
JavaScript for IntermediateProgress 0%
1.1Block Scope with let & const1.2Template Literals1.3Destructuring Arrays and Objects1.4Default Parameters1.5Enhanced Object Literals
7.1Callbacks7.2Promises Basics7.3Promise Chaining7.4Intro to Async/Await
HomeTutorialsJavaScript for IntermediatePromise Chaining
Intro to Async/Await

Promise Chaining

Beginner12 min read•Updated: 2026-09-15•By Er. Sumit Kumar (MSK Institute)
Study Materials

One of the greatest advantages of Promises over callbacks is Promise Chaining. Because .then() always returns a brand-new Promise, you can chain sequential asynchronous operations into a clean, flat, readable pipeline with centralized error handling.


1. How Chaining Works

Whenever you return a value inside a .then() handler, the next .then() receives that value wrapped in a resolved Promise:

1Promise.resolve(5)
2 .then(num => {
3 console.log('Step 1:', num); // 5
4 return num * 2; // Returns 10
5 })
6 .then(doubled => {
7 console.log('Step 2:', doubled); // 10
8 return doubled + 20; // Returns 30
9 })
10 .then(finalSum => {
11 console.log('Step 3:', finalSum); // 30
12 });

2. Returning Promises Inside .then()

If you return a new Promise from inside a .then() callback, the chain will pause until that inner Promise settles:

1function fetchUser(userId) {
2 return Promise.resolve({ id: userId, name: 'Elena' });
3}
4 
5function fetchUserPermissions(userId) {
6 return Promise.resolve(['read', 'write', 'admin']);
7}
8 
9// Flat, sequential asynchronous chain:
10fetchUser(101)
11 .then(user => {
12 console.log(`Fetched user: ${user.name}`);
13 return fetchUserPermissions(user.id); // Returning another Promise!
14 })
15 .then(permissions => {
16 console.log('Fetched permissions:', permissions);
17 })
18 .catch(err => {
19 console.error('Error occurred anywhere in the chain:', err);
20 });

3. Centralized Error Handling

In a Promise chain, errors trickle down until they find the nearest .catch() handler. A single .catch() at the end can handle errors originating from any preceding step:

1fetchUserProfile()
2 .then(profile => validateProfile(profile))
3 .then(validData => saveToDatabase(validData))
4 .then(record => sendConfirmationEmail(record.email))
5 .catch(error => {
6 // Catches validation failures, database errors, OR email errors!
7 console.error('Pipeline failed:', error.message);
8 });

4. Recovering from Errors in a Chain

If you return a fallback value from inside .catch(), subsequent .then() handlers can continue execution:

1function loadCachedConfig() {
2 return { theme: 'default', offline: true };
3}
4 
5fetchRemoteConfig()
6 .catch(err => {
7 console.warn('Remote config failed, falling back to cache...');
8 return loadCachedConfig(); // Recover by returning fallback
9 })
10 .then(config => {
11 console.log('Active configuration:', config); // Executes successfully!
12 });

5. Parallel Promise Combinators

When operations are independent and do not rely on each other, run them concurrently:

MethodBehaviorResolves When...Rejects When...
Promise.all()Fail-fast parallel batchAll fulfillAny single promise rejects
Promise.allSettled()Complete auditAll settle (fulfilled or rejected)Never rejects
Promise.race()First responderFirst promise settlesFirst promise settles
Promise.any()First successFirst promise fulfillsAll promises reject (AggregateError)
1// Run 3 independent API requests simultaneously:
2const [users, products, settings] = await Promise.all([
3 fetch('/api/users').then(r => r.json()),
4 fetch('/api/products').then(r => r.json()),
5 fetch('/api/settings').then(r => r.json())
6]);

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What does a .then() handler return if it does not contain an explicit return statement?
Question 2
How does Promise.all() behave if one of the promises in the array rejects?
Question 3
Which Promise method waits for all promises to finish and returns an array of status objects ({ status, value/reason }) without rejecting?
Question 4
If an error is thrown inside the first .then() of a 4-step chain, where does control jump?
Question 5
What is the primary difference between Promise.any() and Promise.race()?
Next Lesson

Intro to Async/Await

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Promises BasicsIntro to Async/Await

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Intermediate with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext