to-promise-event
v1.0.0
Published
A utility package that creates PromiEvent-like objects, combining promises and event emitters for asynchronous operations.
Readme
to-promise-event
A utility package that creates PromiEvent-like objects, combining promises and event emitters for asynchronous operations.
Installation
Install to-promise-event as a dependency:
npm install to-promise-eventAPI
This package provides a single function for creating promise-event objects.
toPromiseEvent
Converts a function that accepts an event emitter and returns a promise into a "promise event" object, which exposes the promise and the event emitter, both in a sync fashion.
toPromiseEvent<T>(callback: (emitter: EventEmitter<T>) => Promise<void>): {
emitter: EventEmitter<T>;
promise: Promise<void>;
}- callback:
(emitter: EventEmitter<T>) => Promise<void>— A function that receives an event emitter and returns a promise (required)
Example:
import { toPromiseEvent } from "to-promise-event";
const { emitter, promise } = toPromiseEvent(async (emitter) => {
// Emit events during async operation
emitter.emit("progress", 0.5);
// Do some async work
await someAsyncOperation();
emitter.emit("complete", "done");
});
// Listen to events
emitter.on("progress", (progress) => {
console.log(`Progress: ${progress * 100}%`);
});
emitter.on("complete", (result) => {
console.log(`Completed: ${result}`);
});
// Await the promise
await promise;Local Setup
To install the dependencies, run:
npm installTo run the tests, run:
npm test