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
Error Handling in Async Code0%
Study Materials
JavaScript for IntermediateProgress 0%
1.1Block Scope with let & const1.2Template Literals1.3Destructuring Arrays and Objects1.4Default Parameters1.5Enhanced Object Literals
9.1try...catch9.2finally block9.3Throwing Custom Errors9.4Error Handling in Async Code
HomeTutorialsJavaScript for IntermediateError Handling in Async Code
What are Modules?

Error Handling in Async Code

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

Asynchronous operations represent the most common source of runtime failures in web applications—from intermittent network drops to API rate limits and aborted timeouts. Understanding how errors propagate across Promises, async/await, and event loops is essential for production stability.


1. Async/Await with try...catch

The cleanest and most readable pattern for handling asynchronous errors is wrapping await calls in standard try...catch blocks:

1async function fetchUserDashboard(userId) {
2 try {
3 const response = await fetch(`/api/users/${userId}`);
4
5 if (!response.ok) {
6 throw new Error(`API returned HTTP status ${response.status}`);
7 }
8 
9 const userData = await response.json();
10 return userData;
11 } catch (error) {
12 console.error(`Dashboard fetch failed for user ${userId}:`, error.message);
13 // Return fallback state or rethrow
14 return { error: true, message: 'Unable to load dashboard data' };
15 }
16}

2. The Unhandled Promise Rejection Hazard

If a Promise is rejected and has no .catch() handler and is not caught inside a try...catch, JavaScript triggers an UnhandledPromiseRejection:

1 Rejected Promise
2 │
3 Is there a handler?
4 ┌────────┴────────┐
5 YES NO
6 │ │
7 ▼ ▼
8 .catch() / UnhandledPromiseRejection
9 try...catch (Node.js process terminates /
10 Browser logs red console error)

Global Safety Nets

Always register global handlers to capture any stray unhandled rejections:

1// In Modern Browsers:
2window.addEventListener('unhandledrejection', (event) => {
3 console.warn(`UNHANDLED PROMISE REJECTION: ${event.reason}`);
4 // Log to error tracking service (e.g. Sentry)
5 event.preventDefault(); // Suppress default browser error log
6});
7 
8// In Node.js:
9process.on('unhandledRejection', (reason, promise) => {
10 console.error('Unhandled Rejection at:', promise, 'reason:', reason);
11});

3. Go-Style Tuple Pattern for Clean Async Handling

Some developers prefer avoiding nested try...catch blocks by wrapping async operations in a helper that returns a [data, error] tuple (inspired by Go):

1async function to(promise) {
2 try {
3 const data = await promise;
4 return [data, null];
5 } catch (error) {
6 return [null, error];
7 }
8}
9 
10// Usage:
11async function loadFeed() {
12 const [data, err] = await to(fetchFeedFromNetwork());
13 if (err) {
14 console.error('Failed to load feed:', err);
15 return;
16 }
17 console.log('Feed loaded:', data);
18}

4. Error Handling with Promise.allSettled()

When running multiple independent operations in parallel, Promise.all() fails fast if any single promise rejects. To inspect every outcome and handle errors individually, use Promise.allSettled():

1const userIds = [1, 2, 9999, 4]; // 9999 is an invalid ID
2 
3const results = await Promise.allSettled(
4 userIds.map(id => fetchUserById(id))
5);
6 
7results.forEach((result, index) => {
8 if (result.status === 'fulfilled') {
9 console.log(`User ${userIds[index]} loaded:`, result.value.name);
10 } else {
11 console.warn(`User ${userIds[index]} failed:`, result.reason.message);
12 }
13});

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What happens in modern Node.js environments when a Promise rejection is left unhandled?
Question 2
What browser event fires whenever a Promise rejects without a local catch handler?
Question 3
Why is Promise.allSettled() preferred over Promise.all() when fetching data for independent dashboard widgets?
Question 4
In an async function, how does a rejected Promise inside an await expression manifest?
Question 5
What property on each result object of Promise.allSettled() indicates whether the operation succeeded?
Next Lesson

What are Modules?

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

Related Lessons

Previous LessonNext Lesson
Throwing Custom ErrorsWhat are Modules?

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