What is p-event?
The p-event package is a utility for converting event emitters into promises. It allows you to wait for an event to be emitted, making it easier to work with asynchronous event-driven code.
What are p-event's main functionalities?
Wait for a single event
This feature allows you to wait for a single event to be emitted. The promise resolves with the event data when the event is emitted.
const pEvent = require('p-event');
const EventEmitter = require('events');
const emitter = new EventEmitter();
(async () => {
const eventData = await pEvent(emitter, 'data');
console.log(eventData); // Logs the data emitted
})();
emitter.emit('data', 'Hello, world!');
Wait for multiple events
This feature allows you to wait for multiple events to be emitted. The promise resolves when all specified events have been emitted.
const pEvent = require('p-event');
const EventEmitter = require('events');
const emitter = new EventEmitter();
(async () => {
const [data1, data2] = await Promise.all([
pEvent(emitter, 'data1'),
pEvent(emitter, 'data2')
]);
console.log(data1, data2); // Logs the data emitted by both events
})();
emitter.emit('data1', 'First event');
emitter.emit('data2', 'Second event');
Timeout for events
This feature allows you to specify a timeout for waiting for an event. If the event is not emitted within the specified time, the promise is rejected.
const pEvent = require('p-event');
const EventEmitter = require('events');
const emitter = new EventEmitter();
(async () => {
try {
const eventData = await pEvent(emitter, 'data', {timeout: 1000});
console.log(eventData);
} catch (error) {
console.error('Event did not occur within 1 second');
}
})();
Filter events
This feature allows you to filter events based on a condition. The promise resolves only when an event that matches the filter condition is emitted.
const pEvent = require('p-event');
const EventEmitter = require('events');
const emitter = new EventEmitter();
(async () => {
const eventData = await pEvent(emitter, 'data', {
filter: data => data === 'specific data'
});
console.log(eventData); // Logs 'specific data'
})();
emitter.emit('data', 'other data');
emitter.emit('data', 'specific data');
Other packages similar to p-event
event-to-promise
The event-to-promise package provides similar functionality by converting event emitters into promises. It allows you to wait for a single event or multiple events, but it does not offer as many advanced features like filtering or timeouts.
promise-event
The promise-event package is another alternative that converts event emitters into promises. It is simpler and more lightweight compared to p-event, but it lacks some of the advanced features such as filtering and timeouts.
await-event
The await-event package allows you to await events in a similar manner to p-event. It provides basic functionality for waiting for events but does not include advanced options like filtering or timeouts.
p-event
Promisify an event by waiting for it to be emitted
Useful when you need only one event emission and want to use it with promises or await it in an async function.
It works with any event API in Node.js and the browser (using a bundler).
If you want multiple individual events as they are emitted, you can use the pEventIterator()
method. Observables can be useful too.
Install
npm install p-event
Usage
In Node.js:
import {pEvent} from 'p-event';
import emitter from './some-event-emitter';
try {
const result = await pEvent(emitter, 'finish');
console.log(result);
} catch (error) {
console.error(error);
}
In the browser:
import {pEvent} from 'p-event';
await pEvent(document, 'DOMContentLoaded');
console.log('😎');
Async iteration:
import {pEventIterator} from 'p-event';
import emitter from './some-event-emitter';
const asyncIterator = pEventIterator(emitter, 'data', {
resolutionEvents: ['finish']
});
for await (const event of asyncIterator) {
console.log(event);
}
API
pEvent(emitter, event, options?)
pEvent(emitter, event, filter)
Returns a Promise
that is fulfilled when emitter
emits an event matching event
, or rejects if emitter
emits any of the events defined in the rejectionEvents
option.
Note: event
is a string for a single event type, for example, 'data'
. To listen on multiple
events, pass an array of strings, such as ['started', 'stopped']
.
The returned promise has a .cancel()
method, which when called, removes the event listeners and causes the promise to never be settled. However, for new code, it's recommended to use the signal
option instead.
emitter
Type: object
Event emitter object.
Should have either a .on()
/.addListener()
/.addEventListener()
and .off()
/.removeListener()
/.removeEventListener()
method, like the Node.js EventEmitter
and DOM events.
event
Type: string | string[]
Name of the event or events to listen to.
If the same event is defined both here and in rejectionEvents
, this one takes priority.
options
Type: object
rejectionEvents
Type: string[]
Default: ['error']
Events that will reject the promise.
multiArgs
Type: boolean
Default: false
By default, the promisified function will only return the first argument from the event callback, which works fine for most APIs. This option can be useful for APIs that return multiple arguments in the callback. Turning this on will make it return an array of all arguments from the callback, instead of just the first argument.
Example:
import {pEvent} from 'p-event';
import emitter from './some-event-emitter';
const [foo, bar] = await pEvent(emitter, 'finish', {multiArgs: true});
rejectionMultiArgs
Type: boolean
Default: false
By default, rejection events will only return the first argument from the event callback. Turning this on will make it return an array of all arguments from the rejection event callback.
Example:
import {pEvent} from 'p-event';
import emitter from './some-event-emitter';
try {
await pEvent(emitter, 'finish', {rejectionMultiArgs: true});
} catch (error) {
console.log(error);
}
timeout
Type: number
Default: Infinity
Time in milliseconds before timing out.
filter
Type: Function
A filter function for accepting an event. Can be synchronous or asynchronous.
import {pEvent} from 'p-event';
import emitter from './some-event-emitter';
const result = await pEvent(emitter, '🦄', value => value > 3);
const result2 = await pEvent(emitter, 'data', async value => {
const isValid = await validateWithAPI(value);
return isValid;
});
[!NOTE]
If the filter function throws an error or returns a rejected promise, the promise returned by pEvent
will be rejected with that error. If you want to handle filter errors gracefully, wrap your filter logic in a try-catch block and return false
for invalid events.
signal
Type: AbortSignal
An AbortSignal
to abort waiting for the event.
pEventMultiple(emitter, event, options)
Wait for multiple event emissions. Returns an array.
This method has the same arguments and options as pEvent()
with the addition of the following options:
options
Type: object
count
Required
Type: number
The number of times the event needs to be emitted before the promise resolves.
resolveImmediately
Type: boolean
Default: false
Whether to resolve the promise immediately. Emitting one of the rejectionEvents
won't throw an error.
Note: The returned array will be mutated when an event is emitted.
Example:
import {pEventMultiple} from 'p-event';
const emitter = new EventEmitter();
const promise = pEventMultiple(emitter, 'hello', {
resolveImmediately: true,
count: Infinity
});
const result = await promise;
console.log(result);
emitter.emit('hello', 'Jack');
console.log(result);
emitter.emit('hello', 'Mark');
console.log(result);
emitter.emit('error', new Error('😿'));
emitter.emit('hello', 'John');
console.log(result);
pEventIterator(emitter, event, options?)
pEventIterator(emitter, event, filter)
Returns an async iterator that lets you asynchronously iterate over events of event
emitted from emitter
. The iterator ends when emitter
emits an event matching any of the events defined in resolutionEvents
, or rejects if emitter
emits any of the events defined in the rejectionEvents
option.
This method has the same arguments and options as pEvent()
with the addition of the following options:
options
Type: object
limit
Type: number
(non-negative integer)
Default: Infinity
The maximum number of events for the iterator before it ends. When the limit is reached, the iterator will be marked as done
. This option is useful to paginate events, for example, fetching 10 events per page.
resolutionEvents
Type: string[]
Default: []
Events that will end the iterator.
TimeoutError
Exposed for instance checking and sub-classing.
Example:
import {pEvent} from 'p-event';
try {
await pEvent(emitter, 'finish');
} catch (error) {
if (error instanceof pEvent.TimeoutError) {
}
}
Before and after
import fs from 'node:fs';
function getOpenReadStream(file, callback) {
const stream = fs.createReadStream(file);
stream.on('open', () => {
callback(null, stream);
});
stream.on('error', error => {
callback(error);
});
}
getOpenReadStream('unicorn.txt', (error, stream) => {
if (error) {
console.error(error);
return;
}
console.log('File descriptor:', stream.fd);
stream.pipe(process.stdout);
});
import fs from 'node:fs';
import {pEvent} from 'p-event';
async function getOpenReadStream(file) {
const stream = fs.createReadStream(file);
await pEvent(stream, 'open');
return stream;
}
(async () => {
const stream = await getOpenReadStream('unicorn.txt');
console.log('File descriptor:', stream.fd);
stream.pipe(process.stdout);
})()
.catch(console.error);
Tips
Migrating from .cancel()
to AbortSignal
If you're using .cancel()
in existing code, here's how to migrate to the preferred AbortSignal
approach:
const promise = pEvent(emitter, 'finish');
promise.cancel();
const controller = new AbortController();
const promise = pEvent(emitter, 'finish', {
signal: controller.signal
});
controller.abort();
Dealing with calls that resolve with an error code
Some functions might use a single event for success and for certain errors. Promises make it easy to have combined error handler for both error events and successes containing values which represent errors.
import {pEvent} from 'p-event';
import emitter from './some-event-emitter';
try {
const result = await pEvent(emitter, 'finish');
if (result === 'unwanted result') {
throw new Error('Emitter finished with an error');
}
console.log(result);
} catch (error) {
console.error(error);
}
Related
- pify - Promisify a callback-style function
- p-map - Map over promises concurrently
- More…