A respository for npm lt-event-promise
Same as node module events.EventEmitter but return Promise of executing listeners when call emit()
Using npm
npm i lt-event-promise
With node
const EventPromise = require('lt-event-promise')
const emitter = new EventPromise()
With client using webpack
import EventPromise from 'lt-event-promise'
const emitter = new EventPromise()
emitter.on('hello', () => console.log('Hello world!'))
emitter.emit('hello')
Hello world!
emitter.on('task', longTask)
emitter.emit('task')
.then(console.log)
function longTask() {
return new Promise(resolve => {
setTimeout(() => resolve('data'), 2000)
})
}
[ 'data' ]
emitter.on('task', task1, task2)
emitter.emit('task')
.then(console.log)
function task1() { return 'data1' }
function task2() { return 'data2' }
[ 'data1', 'data2' ]
emitter.on('task', task, errorTask)
emitter.emit('task')
.then(console.log)
.catch(err => {
console.log('catch error here')
console.log(err)
})
function task() { return 'data' }
function errorTask() { throw new Error('Something went wrong!') }
'catch error here'
...
throw new Error('Something went wrong!')
^
Error: Something went wrong!
...
emitter.on('task', task1, task2)
try {
let datas = await emitter.emit('task')
console.log(datas)
} catch(err) {
console.error(err)
}
[ 'data1', 'data2' ]
emitter.on('task', onTask)
emitter.once('task', onceTask)
emitter.emit('task')
.then(datas => console.log('First emit:', datas))
emitter.emit('task')
.then(datas => console.log('Next emit:', datas))
function onTask() { return 'onData' }
function onceTask() { return 'onceData' }
First emit: [ 'onData', 'onceData' ]
Next emit: [ 'onData' ]
MIT