FrontendInterviews.dev

Loading problem…

14. Promise Constructor Polyfill

Hard•
Acceptance: 89.47%
•
🔓3/3 Pro unlocks today

Implement a Promise constructor from scratch that follows the Promise/A+ specification. This is the foundation for all Promise methods.

Create a MyPromise class that behaves like the native Promise constructor, supporting:

  • Promise states: pending, fulfilled, rejected
  • then method for chaining
  • catch method for error handling
  • finally method for cleanup
  • Proper microtask scheduling

Requirements

1. Basic Promise Behavior

  • Accept an executor function (resolve, reject) => {}
  • Support three states: pending, fulfilled, rejected
  • State transitions are one-way (pending → fulfilled/rejected)
  • Store resolved/rejected value

2. Then Method

  • Accept onFulfilled and onRejected callbacks
  • Return a new Promise for chaining
  • Handle missing callbacks (value/error propagation)
  • Support promise chaining and value transformation

3. Error Handling

  • Unhandled rejections should be caught
  • Errors in callbacks should be caught and rejected
  • Support catch and finally methods

4. Microtask Scheduling

  • Callbacks should execute asynchronously (microtasks)
  • Use queueMicrotask or setTimeout as fallback

Example Usage

// Basic promise
const p1 = new MyPromise((resolve, reject) => {
  setTimeout(() => resolve('success'), 100);
});

p1.then(value => console.log(value)); // 'success'

// Error handling
const p2 = new MyPromise((resolve, reject) => {
  reject('error');
});

p2.catch(err => console.log(err)); // 'error'

// Chaining
new MyPromise(resolve => resolve(1))
  .then(x => x + 1)
  .then(x => x * 2)
  .then(console.log); // 4

Constraints

  • Must support Promise states: pending, fulfilled, rejected
  • Must support then method with onFulfilled and onRejected callbacks
  • Must return new Promise from then for chaining
  • Must handle errors in callbacks and reject appropriately
  • Must execute callbacks asynchronously (microtasks)
  • Must support catch and finally methods