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

promisify-event-emitter

v0.1.0

Published

Class for promisification any event emitters

Downloads

15

Readme

promisify-event-emitter

Class for promisification EventEmitter like objects.

Installation

npm package

> npm install --save promisify-event-emitter
const PromisifyEventEmitter = require('promisify-event-emitter');

Quickstart

const EventEmitter = require('events');
const emitter = new EventEmitter();

const eventPromise = PromisifyEmitter.on(emitter, 'connect', 'error')
    .then(([user, connection]) => {
        console.log(user, connection) // 'Ivan', {}
    })
    .catch(([reason]) => {
        console.error(reason) // connection refused
    });


emitter.emit('connect', 'Ivan', {}); // in this case eventPromise become fullfilled
emitter.emit('error', 'connection refused'); // in this case eventPromise become rejected

Use case in server context

const fs = require('fs');
const stream = fs.createWriteStream('file.json');

PromisifyEmitter.on(stream, 'end', 'error')
    .then(() => {
        console.log('finish');
    })
    .catch(([err]) => {
        console.error(err);
    });

Use case in browser context

PromisifyEmitter.on(document, 'keydown')
    .then(console.log) // [Event]

API

Package requires ES6 Promise and Map. This class extends methods from promise-event-emitter class. The examples above use simplified syntax, based on static method 'on'. Next, we describe the full syntax.

constructor(emitter: EventEmitterLikeObject, {on: String, off: String, emit: String})

Create a new instance that will use emitter's native subscriptions and transform them to promise-event-emitter logic.

Second optional argument - object that define method names to access to EventEmitterLikeObject. It should be define when you want promisification for nonstandard EventEmitterLikeObject. By default, constructor will try to find in emitter the following well known methods:

  • on: "addEventListener", "addListener", "on"
  • off: "removeEventListener", "removeListener", "off"
  • emit: "dispatchEvent", "emit"
const http = require('http');
const server = http.createServer();
const emitter = new PromisifyEmitter(server);

void async function handleRequest() {
    try {
        const [req, res] = await emitter.on('request', 'clientError');
        res.end('Hello, World!')
    } catch ([err, socket]) {
        socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
    }
    return handleRequest();
}();

server.listen(5000);

emitter.once(event: String, ...otherArgs) => Promise

Subscribe to the event. Returns a promise that will be fulfill when the event will be emitted. otherArgs will be passed to original subscribe method of EventEmitterLikeObject.

const emitter = new PromisifyEmitter(document);

// this recursive function will log all keydown events
void async function keydownLog() {
  const [{key}] = await emitter.once('keydown', { passive: true });
  console.log(key);
  return keydownLog();
}();

emitter.off(event: String, {toEmitter: Array, toPromiseEmitter: Array}) => Boolean

Second argument is optional.

  • Calls 'off' method of EventEmitterLikeObject with toEmitter arguments.
  • Removes the specified event from the event-callback map.
  • Returns call off method of promise-event-emitter with toPromiseEmitter arguments.
const emitter = new PromisifyEmitter(document);

void async function keydownLog() {
    try {
        const [{key}] = await emitter.once('keydown', { passive: true });
        console.log(key);
        return keydownLog();
    } catch([e]) {
        console.error(e); // after click - 'handler removed'
    }
}();

emitter.once('click')
    .then(() => {
        emitter.off('keydown', {
            toEmitter: [{ passive: true }],
            toPromiseEmitter: ['reject', 'handler removed'] 
        });
    });

emitter.emit(event: String, ...args) => Boolean

Returns the result of the method call 'emit' of EventEmitterLikeObject.

emitter.eventCallbackMap

Each instance of the promify-event-emitter class stores an event-callback Map. This allows any type of data to be used as event.

const event = new Event('myEvent');
emitter.once(event).then(console.log); // [42];
emitter.emit(event, 42);

emitter.emitter

Link to EventEmitterLikeObject that was passed to the constructor.

PromisifyEventEmitter.on(emitter, successEvents: String || [String], rejectEvents: String || [String], options)

Static method. Instead of a thousand words:

return new PromisifyEventEmitter(emitter, options).on(successEvents, rejectEvents);

License

ISC © Letry