lt-event-promise

1.1.3 • Public • Published

event-promise

A respository for npm lt-event-promise

Same as node module events.EventEmitter but return Promise of executing listeners when call emit()

Installing

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()

Basic usage

emitter.on('hello', () => console.log('Hello world!'))
emitter.emit('hello')
Hello world!

Using Promise and async/await

Using Promise
emitter.on('task', longTask)
emitter.emit('task')
  .then(console.log)

function longTask() {
  return new Promise(resolve => {
    setTimeout(() => resolve('data'), 2000)
  })
}
[ 'data' ]
Many listeners
emitter.on('task', task1, task2)
emitter.emit('task')
  .then(console.log)
  
function task1() { return 'data1' }
function task2() { return 'data2' }
[ 'data1', 'data2' ]
Error handling
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!
...
Using async/await
emitter.on('task', task1, task2)

try {
  let datas = await emitter.emit('task')
  console.log(datas)
} catch(err) {
  console.error(err)
}
[ 'data1', 'data2' ]
.on and .once
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' ]

License

MIT

Package Sidebar

Install

npm i lt-event-promise

Weekly Downloads

1

Version

1.1.3

License

MIT

Unpacked Size

5.15 kB

Total Files

4

Last publish

Collaborators

  • linhnt2803