All Projects โ†’ sindresorhus โ†’ Emittery

sindresorhus / Emittery

Licence: mit
Simple and modern async event emitter

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Emittery

Promised Pipe
A ramda.pipe-like utility that handles promises internally with zero dependencies
Stars: โœญ 64 (-94.42%)
Mutual labels:  async, promise
Flowa
๐Ÿ”ฅService level control flow for Node.js
Stars: โœญ 66 (-94.24%)
Mutual labels:  async, promise
Then
๐ŸŽฌ Tame async code with battle-tested promises
Stars: โœญ 908 (-20.77%)
Mutual labels:  async, promise
Awaitkit
The ES8 Async/Await control flow for Swift
Stars: โœญ 709 (-38.13%)
Mutual labels:  async, promise
Node Qiniu Sdk
ไธƒ็‰›ไบ‘SDK๏ผŒไฝฟ็”จ ES2017 async functions ๆฅๆ“ไฝœไธƒ็‰›ไบ‘๏ผŒๆŽฅๅฃๅ็งฐไธŽๅฎ˜ๆ–นๆŽฅๅฃๅฏนๅบ”๏ผŒ่ฝปๆพไธŠๆ‰‹๏ผŒๆ–‡ๆกฃ้ฝๅ…จ
Stars: โœญ 44 (-96.16%)
Mutual labels:  async, promise
Wx Promise Pro
โœจๅผบๅคงใ€ไผ˜้›…็š„ๅพฎไฟกๅฐ็จ‹ๅบๅผ‚ๆญฅๅบ“๐Ÿš€
Stars: โœญ 762 (-33.51%)
Mutual labels:  async, promise
Nodespider
[DEPRECATED] Simple, flexible, delightful web crawler/spider package
Stars: โœญ 33 (-97.12%)
Mutual labels:  async, promise
React Hooks Async
React custom hooks for async functions with abortability and composability
Stars: โœญ 459 (-59.95%)
Mutual labels:  async, promise
Breeze
Javascript async flow control manager
Stars: โœญ 38 (-96.68%)
Mutual labels:  async, promise
Fritzbox.js
โ˜Ž๏ธ The leading AVM Fritz!Box API for NodeJS and JavaScript.
Stars: โœญ 36 (-96.86%)
Mutual labels:  async, promise
P Map
Map over promises concurrently
Stars: โœญ 639 (-44.24%)
Mutual labels:  async, promise
Before After Hook
wrap methods with before/after hooks
Stars: โœญ 49 (-95.72%)
Mutual labels:  async, promise
Posterus
Composable async primitives with cancelation, control over scheduling, and coroutines. Superior replacement for JS Promises.
Stars: โœญ 536 (-53.23%)
Mutual labels:  async, promise
Ws Promise Client
PROJECT MOVED: https://github.com/kdex/ws-promise
Stars: โœญ 6 (-99.48%)
Mutual labels:  async, promise
Kneden
Transpile ES2017 async/await to vanilla ES6 Promise chains: a Babel plugin
Stars: โœญ 517 (-54.89%)
Mutual labels:  async, promise
Vue Loadable
โณ Improve your loading state control with pretty simple methods and helpers.
Stars: โœญ 23 (-97.99%)
Mutual labels:  async, promise
P Iteration
Utilities that make array iteration easy when using async/await or Promises
Stars: โœญ 337 (-70.59%)
Mutual labels:  async, promise
Fun Task
Abstraction for managing asynchronous code in JS
Stars: โœญ 363 (-68.32%)
Mutual labels:  async, promise
Create Request
Apply interceptors to `fetch` and create a custom request function.
Stars: โœญ 34 (-97.03%)
Mutual labels:  async, promise
Emacs Async Await
Async/Await for Emacs
Stars: โœญ 47 (-95.9%)
Mutual labels:  async, promise

Simple and modern async event emitter

Coverage Status

It works in Node.js and the browser (using a bundler).

Emitting events asynchronously is important for production code where you want the least amount of synchronous operations. Since JavaScript is single-threaded, no other code can run while doing synchronous operations. For Node.js, that means it will block other requests, defeating the strength of the platform, which is scalability through async. In the browser, a synchronous operation could potentially cause lags and block user interaction.

Install

$ npm install emittery

Usage

const Emittery = require('emittery');

const emitter = new Emittery();

emitter.on('๐Ÿฆ„', data => {
	console.log(data);
});

const myUnicorn = Symbol('๐Ÿฆ„');

emitter.on(myUnicorn, data => {
	console.log(`Unicorns love ${data}`);
});

emitter.emit('๐Ÿฆ„', '๐ŸŒˆ'); // Will trigger printing '๐ŸŒˆ'
emitter.emit(myUnicorn, '๐Ÿฆ‹');  // Will trigger printing 'Unicorns love ๐Ÿฆ‹'

API

eventName

Emittery accepts strings and symbols as event names.

Symbol event names can be used to avoid name collisions when your classes are extended, especially for internal events.

emitter = new Emittery()

on(eventName | eventName[], listener)

Subscribe to one or more events.

Returns an unsubscribe method.

Using the same listener multiple times for the same event will result in only one method call per emitted event.

const Emittery = require('emittery');

const emitter = new Emittery();

emitter.on('๐Ÿฆ„', data => {
	console.log(data);
});
emitter.on(['๐Ÿฆ„', '๐Ÿถ'], data => {
	console.log(data);
});

emitter.emit('๐Ÿฆ„', '๐ŸŒˆ'); // log => '๐ŸŒˆ' x2
emitter.emit('๐Ÿถ', '๐Ÿ–'); // log => '๐Ÿ–'
Custom subscribable events

Emittery exports some symbols which represent custom events that can be passed to Emitter.on and similar methods.

  • Emittery.listenerAdded - Fires when an event listener was added.
  • Emittery.listenerRemoved - Fires when an event listener was removed.
const Emittery = require('emittery');

const emitter = new Emittery();

emitter.on(Emittery.listenerAdded, ({listener, eventName}) => {
	console.log(listener);
	//=> data => {}

	console.log(eventName);
	//=> '๐Ÿฆ„'
});

emitter.on('๐Ÿฆ„', data => {
	// Handle data
});
Listener data
  • listener - The listener that was added.
  • eventName - The name of the event that was added or removed if .on() or .off() was used, or undefined if .onAny() or .offAny() was used.

Only events that are not of this type are able to trigger these events.

listener(data)

off(eventName | eventName[], listener)

Remove one or more event subscriptions.

const Emittery = require('emittery');

const emitter = new Emittery();

const listener = data => console.log(data);
(async () => {
	emitter.on(['๐Ÿฆ„', '๐Ÿถ', '๐ŸฆŠ'], listener);
	await emitter.emit('๐Ÿฆ„', 'a');
	await emitter.emit('๐Ÿถ', 'b');
	await emitter.emit('๐ŸฆŠ', 'c');
	emitter.off('๐Ÿฆ„', listener);
	emitter.off(['๐Ÿถ', '๐ŸฆŠ'], listener);
	await emitter.emit('๐Ÿฆ„', 'a'); // Nothing happens
	await emitter.emit('๐Ÿถ', 'b'); // Nothing happens
	await emitter.emit('๐ŸฆŠ', 'c'); // Nothing happens
})();
listener(data)

once(eventName | eventName[])

Subscribe to one or more events only once. It will be unsubscribed after the first event.

Returns a promise for the event data when eventName is emitted.

const Emittery = require('emittery');

const emitter = new Emittery();

emitter.once('๐Ÿฆ„').then(data => {
	console.log(data);
	//=> '๐ŸŒˆ'
});
emitter.once(['๐Ÿฆ„', '๐Ÿถ']).then(data => {
	console.log(data);
});

emitter.emit('๐Ÿฆ„', '๐ŸŒˆ'); // Log => '๐ŸŒˆ' x2
emitter.emit('๐Ÿถ', '๐Ÿ–'); // Nothing happens

events(eventName)

Get an async iterator which buffers data each time an event is emitted.

Call return() on the iterator to remove the subscription.

const Emittery = require('emittery');

const emitter = new Emittery();
const iterator = emitter.events('๐Ÿฆ„');

emitter.emit('๐Ÿฆ„', '๐ŸŒˆ1'); // Buffered
emitter.emit('๐Ÿฆ„', '๐ŸŒˆ2'); // Buffered

iterator
	.next()
	.then(({value, done}) => {
		// done === false
		// value === '๐ŸŒˆ1'
		return iterator.next();
	})
	.then(({value, done}) => {
		// done === false
		// value === '๐ŸŒˆ2'
		// Revoke subscription
		return iterator.return();
	})
	.then(({done}) => {
		// done === true
	});

In practice, you would usually consume the events using the for await statement. In that case, to revoke the subscription simply break the loop.

const Emittery = require('emittery');

const emitter = new Emittery();
const iterator = emitter.events('๐Ÿฆ„');

emitter.emit('๐Ÿฆ„', '๐ŸŒˆ1'); // Buffered
emitter.emit('๐Ÿฆ„', '๐ŸŒˆ2'); // Buffered

// In an async context.
for await (const data of iterator) {
	if (data === '๐ŸŒˆ2') {
		break; // Revoke the subscription when we see the value '๐ŸŒˆ2'.
	}
}

It accepts multiple event names.

const Emittery = require('emittery');

const emitter = new Emittery();
const iterator = emitter.events(['๐Ÿฆ„', '๐ŸฆŠ']);

emitter.emit('๐Ÿฆ„', '๐ŸŒˆ1'); // Buffered
emitter.emit('๐ŸฆŠ', '๐ŸŒˆ2'); // Buffered

iterator
	.next()
	.then(({value, done}) => {
		// done === false
		// value === '๐ŸŒˆ1'
		return iterator.next();
	})
	.then(({value, done}) => {
		// done === false
		// value === '๐ŸŒˆ2'
		// Revoke subscription
		return iterator.return();
	})
	.then(({done}) => {
		// done === true
	});

emit(eventName, data?)

Trigger an event asynchronously, optionally with some data. Listeners are called in the order they were added, but executed concurrently.

Returns a promise that resolves when all the event listeners are done. Done meaning executed if synchronous or resolved when an async/promise-returning function. You usually wouldn't want to wait for this, but you could for example catch possible errors. If any of the listeners throw/reject, the returned promise will be rejected with the error, but the other listeners will not be affected.

emitSerial(eventName, data?)

Same as above, but it waits for each listener to resolve before triggering the next one. This can be useful if your events depend on each other. Although ideally they should not. Prefer emit() whenever possible.

If any of the listeners throw/reject, the returned promise will be rejected with the error and the remaining listeners will not be called.

onAny(listener)

Subscribe to be notified about any event.

Returns a method to unsubscribe.

listener(eventName, data)

offAny(listener)

Remove an onAny subscription.

anyEvent()

Get an async iterator which buffers a tuple of an event name and data each time an event is emitted.

Call return() on the iterator to remove the subscription.

const Emittery = require('emittery');

const emitter = new Emittery();
const iterator = emitter.anyEvent();

emitter.emit('๐Ÿฆ„', '๐ŸŒˆ1'); // Buffered
emitter.emit('๐ŸŒŸ', '๐ŸŒˆ2'); // Buffered

iterator.next()
	.then(({value, done}) => {
		// done === false
		// value is ['๐Ÿฆ„', '๐ŸŒˆ1']
		return iterator.next();
	})
	.then(({value, done}) => {
		// done === false
		// value is ['๐ŸŒŸ', '๐ŸŒˆ2']
		// Revoke subscription
		return iterator.return();
	})
	.then(({done}) => {
		// done === true
	});

In the same way as for events, you can subscribe by using the for await statement

clearListeners(eventNames?)

Clear all event listeners on the instance.

If eventNames is given, only the listeners for that events are cleared.

listenerCount(eventNames?)

The number of listeners for the eventNames or all events if not specified.

bindMethods(target, methodNames?)

Bind the given methodNames, or all Emittery methods if methodNames is not defined, into the target object.

import Emittery = require('emittery');

const object = {};

new Emittery().bindMethods(object);

object.emit('event');

TypeScript

The default Emittery class has generic types that can be provided by TypeScript users to strongly type the list of events and the data passed to their event listeners.

import Emittery = require('emittery');

const emitter = new Emittery<
	// Pass `{[eventName]: undefined | <eventArg>}` as the first type argument for events that pass data to their listeners.
	// A value of `undefined` in this map means the event listeners should expect no data, and a type other than `undefined` means the listeners will receive one argument of that type.
	{
		open: string,
		close: undefined
	}
>();

// Typechecks just fine because the data type for the `open` event is `string`.
emitter.emit('open', 'foo\n');

// Typechecks just fine because `close` is present but points to undefined in the event data type map.
emitter.emit('close');

// TS compilation error because `1` isn't assignable to `string`.
emitter.emit('open', 1);

// TS compilation error because `other` isn't defined in the event data type map.
emitter.emit('other');

Emittery.mixin(emitteryPropertyName, methodNames?)

A decorator which mixins Emittery as property emitteryPropertyName and methodNames, or all Emittery methods if methodNames is not defined, into the target class.

import Emittery = require('emittery');

@Emittery.mixin('emittery')
class MyClass {}

const instance = new MyClass();

instance.emit('event');

Scheduling details

Listeners are not invoked for events emitted before the listener was added. Removing a listener will prevent that listener from being invoked, even if events are in the process of being (asynchronously!) emitted. This also applies to .clearListeners(), which removes all listeners. Listeners will be called in the order they were added. So-called any listeners are called after event-specific listeners.

Note that when using .emitSerial(), a slow listener will delay invocation of subsequent listeners. It's possible for newer events to overtake older ones.

FAQ

How is this different than the built-in EventEmitter in Node.js?

There are many things to not like about EventEmitter: its huge API surface, synchronous event emitting, magic error event, flawed memory leak detection. Emittery has none of that.

Isn't EventEmitter synchronous for a reason?

Mostly backwards compatibility reasons. The Node.js team can't break the whole ecosystem.

It also allows silly code like this:

let unicorn = false;

emitter.on('๐Ÿฆ„', () => {
	unicorn = true;
});

emitter.emit('๐Ÿฆ„');

console.log(unicorn);
//=> true

But I would argue doing that shows a deeper lack of Node.js and async comprehension and is not something we should optimize for. The benefit of async emitting is much greater.

Can you support multiple arguments for emit()?

No, just use destructuring:

emitter.on('๐Ÿฆ„', ([foo, bar]) => {
	console.log(foo, bar);
});

emitter.emit('๐Ÿฆ„', [foo, bar]);

Related

  • p-event - Promisify an event by waiting for it to be emitted
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].