Code Monkey home page Code Monkey logo

p-event's Introduction

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

p-event's People

Contributors

aaronfriel avatar bendingbender avatar codetheweb avatar coreyfarrell avatar kevva avatar kmalakoff avatar matthiaskern avatar mjlescano avatar molow avatar raymondfeng avatar richienb avatar schneiderl avatar sindresorhus avatar szmarczak avatar vveisard avatar wtgtybhertgeghgtwtg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

p-event's Issues

Undefined rejection

I'm trying to handle custom rejection events. When either of the events in rejection events fires, the error is undefined. The timeout failure does work properly.

try {
    await pEvent(this, 'submit-success', {
         rejectionEvents: ['submit-failure', 'submit-cooldown'],
         timeout: 30000
    });
    console.log('Submit success');
} catch (error) {
    console.log(error);
    if (error instanceOf pEvent.TimeoutError) {
        console.log('this was a timeout')
    }
    if (error === 'submit-cooldown') {
        //How do I get to here?
    }
}

Ability to identify a timeout error

Right now, the only way to identify the error (that I can think of) as a timeout error instead of an error thrown by my emitter or the filter is by checking the err.message and I'm not totally comfortable using the message:

try {
  const result = await pEvent(emitter, 'finish');
  console.log(result);
} catch (err) {
  if (err.message.startsWith('Promise timed out after')) {
    // Do something specific for timeout errors
  }
}

For a clearer and safer way to doing this check, I could send PRs with one or both of these solutions:

  1. Expose module.exports.TimeoutError = pTimeout.TimeoutError to be able to do err instanceof TimeoutError without having to add the p-timeout dependency.
  2. Add on the module p-timeout a err.code = 'TIMEOUT_ERROR' to be able to check it by the code

Jest fails on tests: Cannot use import statement outside a module

After updating to 5.0.1 my tests fail:

 /path/to/project/node_modules/p-event/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import pTimeout from 'p-timeout';
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

Possible Race Condition when catching native events

We are using a networking library (libp2p) which has a transitive dependency on pEvent. We have identified a race condition where pEvent misses the 'open' event emitted by a DataChannel. The code in pEvent appears to synchronously build up a set of Promises to implement it's functionality, so it appears this race condition would not be possible. However, I wonder if because the 'open' event is being emitted by native code, the event can in fact be raised while pEvent is setting up its event handler.

We have a reproducible problem, with a functioning workaround, so we have a pretty high level of confidence that this is what is happening. I don't have anyway to verify, but it seems that this issue could also occur with any other 'native' events, such as DOM events, etc.

The details on the issue are captured in this issue on the downstream library:
libp2p/js-libp2p#2443

Reorder `normalizeEmitter` with `addEventListener` and `removeEventListener` before `on` and `off` to standardize behavior between environments

Node's EventTarget on/ off handlers are different than its add/ remove listener handlers. In my case, this changed the behavior of p-event with MessagePort between node and bun. It makes sense to prioritize add/ remove listener handlers, which are standardized between node and web/ bun/ deno.

I would also like the type definitions to be more accurate, because this caught me by surprise.

Can't build with this as a dependency

./node_modules/p-event/index.js Module parse failed: Unexpected token (29:3) You may need an appropriate loader to handle this file type. | multiArgs: false, | resolveImmediately: false, | ...options | }; |

pEvent.iterator mishandles rejectionEvents

EventEmitter in this script emits two values followed by an error:

const pEvent = require("p-event");
const { EventEmitter } = require("events");

const m = new EventEmitter();

(async () => {
  try {
    for await (const value of pEvent.iterator(m, "value", {
      resolutionEvents: ["end"],
      rejectionEvents: ["error"],
    })) {
      console.log(`value ${value}`);
    }
    console.log("end");
  } catch (err) {
    console.log(`error ${err}`);
  }
})();

void setTimeout(() => {
  m.emit("value", 1);
  m.emit("value", 2);
  m.emit("error", new Error("xxxx"));
}, 100);

I expect pEvent.iterator to yield two values, and then throw an error:

value 1
value 2
error xxxx

However, as of v4.2.0, pEvent.iterator yields the first value, eats the second value, and then ends the iterator normally without throwing the error:

value 1
end

Clear timeout when cancelled?

I feel like a more intuitive behaviour would be when the timeout is cleared when I cancel the promise. Like this when I cancel, I'm still getting the timeout errors which are not really what I was expecting when calling .cancel().

Maybe this is even an issue for p-timeout (to be able to clear the timeout from outside).

I'll happily help out with a PR here.

pEvent does not reliably return when used on same key twice

I'm trying to use p-event in a test case. I have a key-value implementation which is watching a key. There should be a 'change' event fired when I create the watch, and then a second event fired if the key changes:

import * as promiseTools from 'promise-tools';
import pEvent from 'p-event';

        it('should watch a key', async function() {
            const stub = sinon.stub();

            await kv.setKey('foo', { foo: 1 });

            const watch = kv.watchKey('foo');
            watch.on('change', stub);

            await promiseTools.whilst(() => stub.callCount !== 1, () => promiseTools.delay(100));

            await kv.setKey('foo', { foo: 2 });

            await promiseTools.whilst(() => stub.callCount !== 2, () => promiseTools.delay(100));

            sinon.assert.calledTwice(stub);
            sinon.assert.calledWith(stub, { watch, key: 'foo', value: { foo: 1 } });
            sinon.assert.calledWith(stub, { watch, key: 'foo', value: { foo: 2 } });
        });

        it('should watch a key', async function() {
            await kv.setKey('foo2', { foo: 1 });

            const watch = kv.watchKey('foo2');
            const e1 = await pEvent(watch, 'change');
            expect(e1).to.eql({watch, key: 'foo2', value: {foo: 1}});

            await kv.setKey('foo', { foo: 2 });

            console.log('here');
            const e2 = await pEvent(watch, 'change');
            expect(e2).to.eql({watch, key: 'foo2', value: {foo: 2}});
        });

These two test cases ought to be equivalent, but the first one passes reliably, and the second one prints "here" and then times out waiting for the second await (but passes rarely). Am I missing something here?

Timeout and cancel

Just looking through the code, I see a few potential issues:

  • Event listeners stay in place on timeout
    • Timeout should cancel?
  • Cancel binding lost when wrapped in pTimeout

Incompatible with EdgeHTML 16

I get an error when trying to use p-event with EdgeHTML 16. Looking at the code, I think it is the use of the ...args / rest syntax.

Support for async filter function

Thank you for your work and effort on this nice little package, it is exactly what I was looking for!

However, I need the verify the event data by making an async API call. It would be great if the filter option was to support asynchronous functions.

Handle multiple events

Sometimes it might be useful to handle multiple events and gather them. The problem is determining when it's done. Either the user would choose how many events to wait for, or they would choose an event that indicates it's done. I'm not entirely sure how to design this. Should it be part of the existing API or a pEvent.multi() method? What should the options be?

If anyone needs this, please add your use-case so I can be better informed on how to design this.

Process suddenly terminating with exit code 0

I was experimenting with pEvent.iterator with fs.createReadStream. See this very simple example:

// what.js
const pEvent = require('p-event');
const fs = require('fs');

(async () => {
	try {
		console.log('A');
		const asyncIterator = pEvent.iterator(fs.createReadStream('.npmrc'), 'data');
		console.log('B');
		for await (const event of asyncIterator) {
			console.log('C', event.toString());
		}
		console.log('D');
	} catch {
		console.log('E');
	}
})();

Executing node what.js && echo success gives:

A
B
C package-lock=false
success

It does not log D nor E, and even exits with code 0! Do you have any idea what is going on here?

Emitter "succeeding" but returning undefined

I'm using p-Event like this:

const httpServer = await pEvent(server.koaApp.listen(config.server.port), 'listening')

The 'listening' event is triggering but the result in httpServer is undefined. What am I doing wrong?

Thoughts on pattern matching

I have a case where I'm listening to an event emitter, but waiting for a specific pattern in the emitted data. Is this a case that you would be interested in supporting with this module?

pEvent(emitter, 'eventname', (data) => data.id === 5).then(() => {});

Needs timeout option

It is often that you want to wait for something for some time and then just abort, or want​ to track some event not firing.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.