JavaScript is known for its asynchronous nature, enabling operations like data fetching, animations, and file handling without blocking other processes. Promises are at the heart of handling asynchronous operations gracefully, making our code cleaner and more manageable. This project, XPromise, is a custom implementation of JavaScript Promises, helping us explore how the Promise mechanism works internally.
You can check out the full implementation on GitHub.
A Promise in JavaScript is a special object representing the eventual completion or failure of an asynchronous operation. With Promises, we can queue up operations to run after the completion of a task, even if we don’t know when it will be done. Here’s what makes a Promise unique:
Creating a custom Promise, like XPromise, provides a deeper understanding of its inner workings:
Let’s go through the code for XPromise, exploring each component that makes it work just like JavaScript’s native Promises.
XPromise starts by defining three states: PENDING, FULFILLED, and REJECTED.
const PENDING = "PENDING"; const FULFILLED = "FULFILLED"; const REJECTED = "REJECTED"; class XPromise { constructor(executor) { this.state = PENDING; this.queue = []; doResolve(this, executor); } // ... }
With then, catch, and finally, we handle fulfilled, rejected, and cleanup scenarios. Here’s how XPromise achieves chaining:
const PENDING = "PENDING"; const FULFILLED = "FULFILLED"; const REJECTED = "REJECTED"; class XPromise { constructor(executor) { this.state = PENDING; this.queue = []; doResolve(this, executor); } // ... }
The handle function decides if the Promise is still pending or resolved. If it’s pending, the handler is added to the queue to be executed later. If the Promise is resolved, it immediately processes the handler.
then(onFulfilled, onRejected) { const promise = new XPromise(() => {}); handle(this, { promise, onFulfilled, onRejected }); return promise; } catch(onRejected) { return this.then(null, onRejected); } finally(onFinally) { return this.then(onFinally, onFinally); }
Fulfilled and rejected Promises need special functions to handle their results. Here’s how XPromise achieves it:
function handle(promise, handler) { while (promise.state !== REJECTED && promise.value instanceof XPromise) { promise = promise.value; } if (promise.state === PENDING) { promise.queue.push(handler); } else { handleResolved(promise, handler); } }
Fulfill and Reject:
Finalizing Queued Handlers:
The doResolve function runs the executor safely by wrapping resolve and reject calls, preventing any further state changes if they are called multiple times.
function fulfill(promise, value) { if (value === promise) { return reject(promise, new TypeError()); } if (value && (typeof value === "object" || typeof value === "function")) { let then; try { then = value.then; } catch (e) { return reject(promise, e); } if (typeof then === "function") { return doResolve(promise, then.bind(value)); } } promise.state = FULFILLED; promise.value = value; finale(promise); } function reject(promise, reason) { promise.state = REJECTED; promise.value = reason; finale(promise); }
Now that we have a working XPromise, let’s try it out with a simple example:
function doResolve(promise, executor) { let called = false; function wrapFulfill(value) { if (called) return; called = true; fulfill(promise, value); } function wrapReject(reason) { if (called) return; called = true; reject(promise, reason); } try { executor(wrapFulfill, wrapReject); } catch (e) { wrapReject(e); } }
Reimplementing Promises from scratch provides hands-on insight into how asynchronous programming is managed in JavaScript:
To dive deeper into the code, check out the XPromise project on GitHub. Experiment with the code and feel free to customize it to explore more advanced features, such as Promise race conditions, chaining, and nesting!
The above is the detailed content of Building XPromise: A Deep Dive into Custom JavaScript Promises. For more information, please follow other related articles on the PHP Chinese website!