aim-promises
Version:
A complete Promise/A+ compatible implementation built from scratch
261 lines (185 loc) โข 6.37 kB
Markdown
//badge.fury.io/js/aim-promises.svg)](https://badge.fury.io/js/aim-promises)
[](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.
- ๐ฏ **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
```bash
npm install aim-promises
```
```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
});
```
```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
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!
});
```
```javascript
new AimPromise(executor);
```
Creates a new AimPromise instance.
- `executor` (Function): A function that is passed with the arguments `resolve` and `reject`
Attaches callbacks for the resolution and/or rejection of the Promise.
```javascript
promise.then((value) => value * 2).then((value) => console.log(value));
```
Attaches a callback for only the rejection of the Promise.
```javascript
promise
.then((value) => JSON.parse(value))
.catch((error) => console.error("Parse error:", error));
```
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());
```
Creates a resolved promise with the given value.
```javascript
AimPromise.resolve(42).then((value) => console.log(value)); // 42
```
Creates a rejected promise with the given reason.
```javascript
AimPromise.reject(new Error("Something went wrong")).catch((error) =>
console.error(error.message)
);
```
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]
});
```
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 }
// ]
});
```
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'
});
```
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!'
```
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
```javascript
new AimPromise((resolve) => resolve(10))
.then((x) => x * 2)
.then((x) => x + 5)
.then((result) => console.log(result)); // 25
```
```javascript
new AimPromise((resolve, reject) => reject("failed"))
.catch((error) => "recovered")
.then((value) => console.log(value)); // 'recovered'
```
```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);
}
}
```
This implementation passes all Promise/A+ specification tests:
- โ
Promise States and Transitions
- โ
Promise Resolution Procedure
- โ
Asynchronous Execution
- โ
Thenable Assimilation
- โ
Error Handling
Contributions are welcome! Please feel free to submit a Pull Request.
MIT License. See [LICENSE](LICENSE) file for details.
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! ๐ฏ
[![npm version](https: