JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • 0
  • Score
    100M100P100Q12491F
  • License MIT

Same as EventEmitter but return Promise of executing listeners when emit()

Package Exports

  • lt-event-promise

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (lt-event-promise) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

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