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
Custom Promise Implementation0%
Study Materials
JavaScript for AdvancedProgress 0%
1.1Higher-Order Functions & Currying1.2Function Composition & Pipelining1.3Memoization & Pure Functions1.4Execution Context & Call Stack Deep Dive1.5Scope Chain & Lexical Environment
4.1Microtasks vs Macrotasks (Event Loop Deep Dive)4.2Custom Promise Implementation4.3Async Generators & For-Await-Of4.4Web Workers & Multithreading in JS
HomeTutorialsJavaScript for AdvancedCustom Promise Implementation
Async Generators & For-Await-Of

Custom Promise Implementation

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

There is no better way to deeply understand asynchronous JavaScript than to build a Promises/A+ compliant Promise class from scratch. This exercise demystifies state transitions, handler queues, and microtask scheduling.


1. The Core Specifications (Promises/A+)

  1. 1
    Three Mutually Exclusive States: PENDING, FULFILLED, REJECTED.
  2. 2
    State Transition Guarantee: PENDING can transition to FULFILLED (with a value) or REJECTED (with a reason). Once settled, state and value are immutable.
  3. 3
    The .then() Method: Returns a new Promise, enabling chaining. Handlers must execute asynchronously via microtasks.

2. Step-by-Step Architecture

1 ┌────────────────────────────────┐
2 │ MyPromise │
3 ├────────────────────────────────┤
4 │ state: PENDING │
5 │ value: undefined │
6 │ fulfilledCallbacks: [] │
7 │ rejectedCallbacks: [] │
8 └───────────────┬────────────────┘
9 │
10 ┌───────────────┴────────────────┐
11 │ resolve(val) / reject(err) │
12 └───────────────┬────────────────┘
13 │
14 queueMicrotask()
15 │
16 ▼
17 Drain registered callbacks

3. The Implementation

1const PENDING = 'PENDING';
2const FULFILLED = 'FULFILLED';
3const REJECTED = 'REJECTED';
4 
5class MyPromise {
6 constructor(executor) {
7 this.state = PENDING;
8 this.value = undefined;
9 this.onFulfilledCallbacks = [];
10 this.onRejectedCallbacks = [];
11 
12 const resolve = (val) => {
13 if (this.state === PENDING) {
14 this.state = FULFILLED;
15 this.value = val;
16 // Drain callbacks asynchronously in microtask
17 queueMicrotask(() => {
18 this.onFulfilledCallbacks.forEach(cb => cb(this.value));
19 });
20 }
21 };
22 
23 const reject = (reason) => {
24 if (this.state === PENDING) {
25 this.state = REJECTED;
26 this.value = reason;
27 queueMicrotask(() => {
28 this.onRejectedCallbacks.forEach(cb => cb(this.value));
29 });
30 }
31 };
32 
33 try {
34 executor(resolve, reject);
35 } catch (err) {
36 reject(err);
37 }
38 }
39 
40 then(onFulfilled, onRejected) {
41 // Ensure handlers are functions; fallback to passthrough
42 const realOnFulfilled = typeof onFulfilled === 'function' ? onFulfilled : val => val;
43 const realOnRejected = typeof onRejected === 'function' ? onRejected : err => { throw err; };
44 
45 // .then() MUST return a brand new Promise!
46 return new MyPromise((resolveNext, rejectNext) => {
47 const handleCallback = (callback) => {
48 try {
49 const result = callback(this.value);
50 // If returned value is itself a thenable/promise, resolve it
51 if (result instanceof MyPromise) {
52 result.then(resolveNext, rejectNext);
53 } else {
54 resolveNext(result);
55 }
56 } catch (error) {
57 rejectNext(error);
58 }
59 };
60 
61 if (this.state === FULFILLED) {
62 queueMicrotask(() => handleCallback(realOnFulfilled));
63 } else if (this.state === REJECTED) {
64 queueMicrotask(() => handleCallback(realOnRejected));
65 } else {
66 // Still PENDING: enqueue handlers
67 this.onFulfilledCallbacks.push(() => handleCallback(realOnFulfilled));
68 this.onRejectedCallbacks.push(() => handleCallback(realOnRejected));
69 }
70 });
71 }
72 
73 catch(onRejected) {
74 return this.then(null, onRejected);
75 }
76 
77 static resolve(val) {
78 return new MyPromise((res) => res(val));
79 }
80 
81 static reject(err) {
82 return new MyPromise((_, rej) => rej(err));
83 }
84}

4. Testing the Implementation

1console.log('1. Start Test');
2 
3const p = new MyPromise((resolve) => {
4 setTimeout(() => resolve('Data Loaded!'), 500);
5});
6 
7p.then((data) => {
8 console.log('2. Step 1 Received:', data);
9 return 'Next Pipeline Step';
10})
11.then((next) => {
12 console.log('3. Step 2 Received:', next);
13});
14 
15console.log('4. End Test');
16 
17// Logs:
18// 1. Start Test
19// 4. End Test
20// (after 500ms):
21// 2. Step 1 Received: Data Loaded!
22// 3. Step 2 Received: Next Pipeline Step

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
Why must the .then() method return a brand-new Promise instance rather than returning this?
Question 2
Why are registered callbacks executed inside queueMicrotask()?
Question 3
What happens if an executor function throws an uncaught synchronous exception?
Question 4
If onFulfilled is not a function in .then(null, onRejected), what default behavior must be implemented?
Question 5
What should happen if a .then() callback returns another Promise instance?
Next Lesson

Async Generators & For-Await-Of

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

Related Lessons

Previous LessonNext Lesson
Microtasks vs Macrotasks (Event Loop Deep Dive)Async Generators & For-Await-Of

Practice Quiz

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

Mentor-Led Practical Training

Master JavaScript for Advanced 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