npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

p-event

v6.0.1

Published

Promisify an event by waiting for it to be emitted

Downloads

25,780,844

Readme

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');

	// `emitter` emitted a `finish` event
	console.log(result);
} catch (error) {
	// `emitter` emitted an `error` event
	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.

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. This also applies to rejections.

Example:

import {pEvent} from 'p-event';
import emitter from './some-event-emitter';

const [foo, bar] = await pEvent(emitter, 'finish', {multiArgs: true});
timeout

Type: number
Default: Infinity

Time in milliseconds before timing out.

filter

Type: Function

A filter function for accepting an event.

import {pEvent} from 'p-event';
import emitter from './some-event-emitter';

const result = await pEvent(emitter, '🦄', value => value > 3);
// Do something with first 🦄 event with a value greater than 3
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);
//=> ['Jack']

emitter.emit('hello', 'Mark');
console.log(result);
//=> ['Jack', 'Mark']

// Stops listening
emitter.emit('error', new Error('😿'));

emitter.emit('hello', 'John');
console.log(result);
//=> ['Jack', 'Mark']

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) {
		// Do something specific for timeout errors
	}
}

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);

Tip

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');
	}

	// `emitter` emitted a `finish` event with an acceptable value
	console.log(result);
} catch (error) {
	// `emitter` emitted an `error` event or
	// emitted a `finish` with 'unwanted result'
	console.error(error);
}

Related

  • pify - Promisify a callback-style function
  • p-map - Map over promises concurrently
  • More…