Technical Interview Challenge: The "Micro-Runtime" Promise Engine
Context
You are part of a team building a specialized, lightweight JavaScript runtime for edge computing. To minimize the binary size, you’ve decided to exclude the full V8 engine and implement core language features manually. One of the most critical components is the Asynchronous Orchestration Layer.
You are tasked with building a custom Promise implementation that adheres to the Promises/A+ behavioral standards, ensuring that asynchronous tasks are handled predictably without blocking the main execution thread.
Problem Statement
Implement a class MyPromise that replicates the core functionality of the native JavaScript Promise. Your implementation must manage state transitions and coordinate the execution of dependent callbacks via the Microtask Queue.
Requirements:
State Management: The promise must transition from
PENDINGto eitherFULFILLEDorREJECTED. Once settled, the state and value must become immutable.Executor Execution: The constructor must take an
executorfunction that receivesresolveandrejectarguments.Asynchronous Chaining:
Implement
.then(onFulfilled, onRejected), which returns a newMyPromiseto allow for chaining.Handlers passed to
.thenmust be executed asynchronously using the microtask queue (e.g.,queueMicrotask), even if the promise is already settled.
Error Handling: Implement
.catch(onRejected)as a shorthand for error management.Value Forwarding: If a
.thenhandler returns a value, the next promise in the chain should resolve with that value. If it returns anotherMyPromise, the chain must wait for that promise to settle before continuing.
Example Use Cases
Example 1: Basic Resolution & Chaining
JavaScript