promise-once-events
v0.2.0
Published
Return promise for events.once method
Downloads
3
Readme
promise-once-events
This module provides promisified version of standard
EventEmitter
class,
except that
once
method returns Promise
object which is fulfilled when
emit
method is called.
Requirements
This module requires Node >= 4. For Node < 6 --harmony
flag is required.
Installation
npm install promise-once-events
Usage
promise-once-events
can be a base class for custom event emitter.
const PromiseOnceEvents = require('promise-once-events')
class MyEmitter extends PromiseOnceEvents {}
const emitter = new MyEmitter()
Method once
returns Promise
object which is fulfilled when emit
method is
called and then result is an Arguments
object which contains arguments from
emit
method.
// As promise
emitter.once('event').then(result => {
// result is object Arguments
console.log('an event occurred with arguments:', result)
})
emitter.emit('event', 'a', 'b')
It also works with async
/await
syntax:
// As promise
const result = await emitter.once('event')
// result is object Arguments
console.log('an event occurred with arguments:', result)
If the last argument for once
method is a callback then it works as for
original EventEmitter.once
method.
// With callback
emitter.once('event', (a, b) => {
console.log('an event occurred with arguments:', [a, b])
})
emitter.emit('event', 'a', 'b')
Overriding EventEmitter
PromiseOnceEvents
can be used as a replacement for EventEmitter
for existing
objects.
Example:
const readable = fs.createReadStream(process.argv[2] || __filename)
readable.once = PromiseOnceEvents.prototype.once
readable.on('data', (chunk) => {
console.log(`Received ${chunk.length} bytes of data.`)
})
await readable.once('end')
console.log('There will be no more data.')
Promise
This module uses any-promise and any ES6 Promise library or polyfill is supported.
Ie. bluebird can be used as Promise library for this module, if it is registered before.
require('any-promise/register/bluebird')
const PromiseOnceEvents = require('promise-once-events')
License
Copyright (c) 2016-2017 Piotr Roszatycki [email protected]