Skip to content

MichaelOstermann/promise

Repository files navigation

promise

Minified Minzipped

Functional utilities for promises.

Documentation

Installation

npm install @monstermann/promise
pnpm add @monstermann/promise
yarn add @monstermann/promise
bun add @monstermann/promise

Tree-shaking

Installation

npm install -D @monstermann/unplugin-promise
pnpm -D add @monstermann/unplugin-promise
yarn -D add @monstermann/unplugin-promise
bun -D add @monstermann/unplugin-promise

Usage

// vite.config.ts
import promise from "@monstermann/unplugin-promise/vite";

export default defineConfig({
    plugins: [promise()],
});
// rollup.config.js
import promise from "@monstermann/unplugin-promise/rollup";

export default {
    plugins: [promise()],
};
// rolldown.config.js
import promise from "@monstermann/unplugin-promise/rolldown";

export default {
    plugins: [promise()],
};
// webpack.config.js
const promise = require("@monstermann/unplugin-promise/webpack");

module.exports = {
    plugins: [promise()],
};
// rspack.config.js
const promise = require("@monstermann/unplugin-promise/rspack");

module.exports = {
    plugins: [promise()],
};
// esbuild.config.js
import { build } from "esbuild";
import promise from "@monstermann/unplugin-promise/esbuild";

build({
    plugins: [promise()],
});

Promise

all

function Promise.all<T>(values: Iterable<T | PromiseLike<T>>): Promise<Awaited<T>[]>

Waits for all promises to resolve and returns an array of their results. If any promise rejects, the entire operation rejects with that reason.

Example

import { Promise } from "@monstermann/promise";

const results = await Promise.all([
    Promise.resolve(1),
    Promise.resolve(2),
    Promise.resolve(3),
]); // [1, 2, 3]

allSettled

function Promise.allSettled<T extends readonly unknown[] | []>(values: T): Promise<{ -readonly [P in keyof T]: PromiseSettledResult<Awaited<T[P]>>; }>

Waits for all promises to settle (resolve or reject) and returns an array of their results with status information.

Example

import { Promise } from "@monstermann/promise";

const results = await Promise.allSettled([
    Promise.resolve(1),
    Promise.reject("error"),
    Promise.resolve(3),
]);
// [
//   { status: "fulfilled", value: 1 },
//   { status: "rejected", reason: "error" },
//   { status: "fulfilled", value: 3 }
// ]

andThen

function Promise.andThen<T, U>(
    target: Promise<T>,
    onResolved: (value: NoInfer<T>) => U | PromiseLike<U>,
    onRejected?:
        | ((reason: any) => U | PromiseLike<U>)
        | null
        | undefined,
): Promise<U>

Transforms resolved promise values with onResolved. This is an alias for Promise.then.

Example

import { Promise } from "@monstermann/promise";

Promise.andThen(Promise.resolve(5), (x) => x * 2); // Promise<10>
import { Promise } from "@monstermann/promise";

pipe(
    Promise.resolve(5),
    Promise.andThen((x) => x * 2),
); // Promise<10>

any

function Promise.any<T extends readonly unknown[] | []>(values: T): Promise<Awaited<T[number]>>

Waits for the first promise to resolve and returns its result. If all promises reject, it rejects with an AggregateError.

Example

import { Promise } from "@monstermann/promise";

const result = await Promise.any([
    Promise.reject("error1"),
    Promise.resolve(2),
    Promise.resolve(3),
]); // 2

create

function Promise.create<T>(
    executor: (
        resolve: (value: T | PromiseLike<T>) => void,
        reject: (reason?: any) => void,
    ) => void,
): Promise<T>

Creates a new promise with an executor function that receives resolve and reject callbacks.

Example

import { Promise } from "@monstermann/promise";

const promise = Promise.create<number>((resolve, reject) => {
    setTimeout(() => resolve(42), 1000);
});

debounce

function Promise.debounce(...args: T): void

Creates a debounced function that delays invoking fn until after options.wait milliseconds have elapsed since the last time the debounced function was invoked.

Implementation details:

  • Only one fn can run at any given time, asynchronous functions can not conflict with each other
  • Pending calls are not accumulated in an internal array and asynchronously resolved

Example

import { Promise } from "@monstermann/promise";

const debouncedSave = Promise.debounce(saveData, {
    wait: 1000,
    // Maximum time to wait after the first call, default: undefined
    maxWait?: 5000,
    // Invoke function on the leading edge, default: false
    leading?: false,
    // Invoke function on the trailing edge, default: true
    trailing?: true,
});

// void
debouncedSave(data);

// Cancel pending execution - does not cancel current invocation
debouncedSave.clear();

// Execute pending invocation asap
debouncedSave.flush();

debouncedSave.isIdle();
debouncedSave.isPending();
debouncedSave.isRunning();

// Wait until idle, if a `gracePeriod` is given then wait
// until it has been idle for `gracePeriod` milliseconds
await debouncedSave.idle(gracePeriod?: number);

defer

function Promise.defer<T = void>(): Deferred<T>

Creates a promise that can be resolved/rejected from the outside.

Example

import { Promise } from "@monstermann/promise";

const deferred = defer<string>();
setTimeout(() => deferred.resolve("completed"), 1000);
const result = await deferred.promise; // "completed"

is

function Promise.is(target: unknown): target is Promise<unknown>

Checks if target is a Promise instance.

Example

import { Promise } from "@monstermann/promise";

Promise.is(Promise.resolve()); // true
Promise.is("hello"); // false

limit

function Promise.limit(...args: T): Promise<Awaited<U>>

Limits the concurrency of function execution.

Example

import { Promise } from "@monstermann/promise";

const limitedFetch = Promise.limit(fetch, { concurrency: 3 });
const limitedFetch2 = Promise.limit(fetch, 3); // Shorthand

const results = await Promise.all([
    // At most 3 fetch calls are executed at any time
    limitedFetch("/api/1"),
    limitedFetch("/api/2"),
    limitedFetch("/api/3"),
    limitedFetch("/api/4"),
]);

// Wait for queue to become idle
await limitedFetch.idle();

orElse

function Promise.orElse<T, U>(
    target: Promise<T>,
    onRejected: (reason: unknown) => U | PromiseLike<U>,
): Promise<T | U>

Catches rejected promises and handles them with onRejected. This is an alias for Promise.catch.

Example

import { Promise } from "@monstermann/promise";

Promise.orElse(Promise.reject("error"), () => "fallback"); // Promise<"fallback">
import { Promise } from "@monstermann/promise";

pipe(
    Promise.reject("error"),
    Promise.orElse(() => "fallback"),
); // Promise<"fallback">

queue

function Promise.queue(options: QueueOptions): Queue

Creates a queue that limits concurrent execution of tasks.

Example

import { Promise } from "@monstermann/promise";

const taskQueue = Promise.queue({ concurrency: 2 });
const taskQueue2 = Promise.queue(2); // shorthand

const results = await Promise.all([
    // At most 2 fetch calls are executed at any time
    taskQueue.add(() => fetchData(1)),
    taskQueue.add(() => fetchData(2)),
    taskQueue.add(() => fetchData(3)),
]);

// Wait for queue to become idle
await taskQueue.idle();

reject

function Promise.reject<T = never>(reason?: any): Promise<T>

Creates a promise that is rejected with the given reason.

Example

import { Promise } from "@monstermann/promise";

const promise = Promise.reject("error"); // Promise<never>

resolve

function Promise.resolve<T>(value: T): Promise<Awaited<T>>

Creates a promise that resolves with the given value. If the value is already a promise, it returns that promise.

Example

import { Promise } from "@monstermann/promise";

const promise = Promise.resolve(42); // Promise<42>

throttle

function Promise.throttle(...args: T): void

Creates a throttled function that limits how often fn can be invoked based on options.wait milliseconds.

Implementation details:

  • Only one fn can run at any given time, asynchronous functions can not conflict with each other
  • Pending calls are not accumulated in an internal array and asynchronously resolved

Example

import { Promise } from "@monstermann/promise";

const throttledSave = Promise.throttle(saveData, {
    wait: 1000,
    // Invoke function on the leading edge, default: false
    leading?: false,
    // Invoke function on the trailing edge, default: true
    trailing?: true,
});

// void
throttledSave(data);

// Cancel pending execution - does not cancel current invocation
throttledSave.clear();

// Execute pending invocation asap
throttledSave.flush();

throttledSave.isIdle();
throttledSave.isPending();
throttledSave.isRunning();

// Wait until idle, if a `gracePeriod` is given then wait
// until it has been idle for `gracePeriod` milliseconds
await throttledSave.idle(gracePeriod?: number);

wait

function Promise.wait(duration: number): Promise<void>

Creates a promise that resolves after duration milliseconds.

Example

import { Promise } from "@monstermann/promise";

await Promise.wait(1000); // waits 1 second
import { Promise } from "@monstermann/promise";

pipe(1000, Promise.wait()); // returns Promise<void>

About

Functional utilities for promises.

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors