UNPKG

aim-promises

Version:

A complete Promise/A+ compatible implementation built from scratch

261 lines (185 loc) โ€ข 6.37 kB
# AimPromises ๐ŸŽฏ [![npm version](https://badge.fury.io/js/aim-promises.svg)](https://badge.fury.io/js/aim-promises) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) A **complete Promise/A+ compatible implementation** built from scratch for educational and production use. This implementation demonstrates every aspect of how Promises work internally, including proper asynchronous execution, thenable resolution, and all standard Promise methods. ## โœจ Features - ๐ŸŽฏ **Full Promise/A+ compliance** - โšก **Proper asynchronous execution** with microtask scheduling - ๐Ÿ”— **Complete thenable support** - works with any Promise-like object - ๐Ÿ›ก๏ธ **Robust error handling** and state management - ๐Ÿ“ฆ **Zero dependencies** - ๐Ÿ”ท **TypeScript support** included - ๐ŸŒ **Universal compatibility** - works in Node.js and browsers - ๐Ÿ“š **Educational** - clean, readable code with detailed comments ## ๐Ÿ“ฆ Installation ```bash npm install aim-promises ``` ## ๐Ÿš€ Quick Start ### CommonJS ```javascript const AimPromise = require("aim-promises"); const promise = new AimPromise((resolve, reject) => { setTimeout(() => resolve("Hello, World!"), 1000); }); promise.then((value) => { console.log(value); // "Hello, World!" after 1 second }); ``` ### ES Modules ```javascript import AimPromise from "aim-promises"; const promise = new AimPromise((resolve, reject) => { setTimeout(() => resolve("Hello, World!"), 1000); }); promise.then((value) => { console.log(value); // "Hello, World!" after 1 second }); ``` ### TypeScript ```typescript import AimPromise from "aim-promises"; const promise = new AimPromise<string>((resolve, reject) => { setTimeout(() => resolve("Hello, TypeScript!"), 1000); }); promise.then((value: string) => { console.log(value); // Fully typed! }); ``` ## ๐Ÿ“– API Reference ### Constructor ```javascript new AimPromise(executor); ``` Creates a new AimPromise instance. - `executor` (Function): A function that is passed with the arguments `resolve` and `reject` ### Instance Methods #### `.then(onFulfilled?, onRejected?)` Attaches callbacks for the resolution and/or rejection of the Promise. ```javascript promise.then((value) => value * 2).then((value) => console.log(value)); ``` #### `.catch(onRejected?)` Attaches a callback for only the rejection of the Promise. ```javascript promise .then((value) => JSON.parse(value)) .catch((error) => console.error("Parse error:", error)); ``` #### `.finally(onFinally?)` Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). ```javascript promise .then((value) => processData(value)) .catch((error) => handleError(error)) .finally(() => cleanup()); ``` ### Static Methods #### `AimPromise.resolve(value?)` Creates a resolved promise with the given value. ```javascript AimPromise.resolve(42).then((value) => console.log(value)); // 42 ``` #### `AimPromise.reject(reason?)` Creates a rejected promise with the given reason. ```javascript AimPromise.reject(new Error("Something went wrong")).catch((error) => console.error(error.message) ); ``` #### `AimPromise.all(iterable)` Waits for all promises to resolve, or rejects if any promise rejects. ```javascript AimPromise.all([ AimPromise.resolve(1), AimPromise.resolve(2), AimPromise.resolve(3), ]).then((values) => { console.log(values); // [1, 2, 3] }); ``` #### `AimPromise.allSettled(iterable)` Waits for all promises to settle (resolve or reject). ```javascript AimPromise.allSettled([ AimPromise.resolve(1), AimPromise.reject("error"), AimPromise.resolve(3), ]).then((results) => { console.log(results); // [ // { status: 'fulfilled', value: 1 }, // { status: 'rejected', reason: 'error' }, // { status: 'fulfilled', value: 3 } // ] }); ``` #### `AimPromise.race(iterable)` Returns the first promise to settle (resolve or reject). ```javascript AimPromise.race([ new AimPromise((resolve) => setTimeout(() => resolve("slow"), 1000)), new AimPromise((resolve) => setTimeout(() => resolve("fast"), 100)), ]).then((value) => { console.log(value); // 'fast' }); ``` ## ๐Ÿ”„ Thenable Support AimPromise fully supports thenables - any object with a `.then()` method: ```javascript const thenable = { then(onFulfilled, onRejected) { onFulfilled("I am a thenable!"); }, }; AimPromise.resolve(thenable).then((value) => console.log(value)); // 'I am a thenable!' ``` ## ๐ŸŽ“ Educational Value This implementation demonstrates: - **State Management**: How promises transition between pending, fulfilled, and rejected states - **Asynchronous Execution**: Proper use of microtasks for consistent behavior - **Promise Resolution Procedure**: The complex algorithm for handling thenables - **Chaining**: How `.then()` creates new promises for seamless chaining - **Error Handling**: Propagation and catching of errors through promise chains ## ๐Ÿงช Examples ### Basic Chaining ```javascript new AimPromise((resolve) => resolve(10)) .then((x) => x * 2) .then((x) => x + 5) .then((result) => console.log(result)); // 25 ``` ### Error Recovery ```javascript new AimPromise((resolve, reject) => reject("failed")) .catch((error) => "recovered") .then((value) => console.log(value)); // 'recovered' ``` ### Async/Await (if your environment supports it) ```javascript async function example() { try { const result = await new AimPromise((resolve) => setTimeout(() => resolve("async result"), 100) ); console.log(result); // 'async result' } catch (error) { console.error(error); } } ``` ## ๐Ÿ“‹ Promise/A+ Compliance This implementation passes all Promise/A+ specification tests: - โœ… Promise States and Transitions - โœ… Promise Resolution Procedure - โœ… Asynchronous Execution - โœ… Thenable Assimilation - โœ… Error Handling ## ๐Ÿค Contributing Contributions are welcome! Please feel free to submit a Pull Request. ## ๐Ÿ“„ License MIT License. See [LICENSE](LICENSE) file for details. ## ๐Ÿ™ Acknowledgments Built to demonstrate the internals of JavaScript Promises and provide a fully-functional alternative for educational and production use. --- **Why AimPromise?** Because understanding how Promises work internally helps you aim for better asynchronous JavaScript! ๐ŸŽฏ