1.0.1 • Published 2 years ago

@cameronhunter/pending-promises v1.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

@cameronhunter/pending-promises

npm package main branch status

A map of pending promises that can be resolved/rejected at a later time.

This data structure helps convert event-based APIs to promise-based. Here's an example that wraps a WebSocket client, providing a promise-based API.

import { PendingPromises } from '@cameronhunter/pending-promises';

class MyAPI {
    readonly #responses: PendingPromises = new PendingPromises();
    readonly #ws: WebSocket;

    constructor(ws: WebSocket) {
        this.#ws = ws;
        this.#ws.on('message', this.#onMessage.bind(this));
    }

    send(message: string): Promise<string> {
        // Create a new pending promise
        const [id, promise] = this.#responses.create<string>();

        ws.send(JSON.stringify({ id, message }), (err) => {
            if (err) {
                // Reject immediately if sending fails.
                this.#responses.reject(id, err);
            }
        });

        return promise;
    }

    #onMessage(event: WebSocket.MessageEvent): void {
        const { id, result, error } = JSON.parse(event.data as string);

        if (id) {
            if (error) {
                this.#responses.reject(id, error);
            } else {
                this.#responses.resolve(id, result);
            }
        }
    }
}