Skip to content

Instantly share code, notes, and snippets.

@dwelch2344
Created March 4, 2021 05:22
Show Gist options
  • Save dwelch2344/6c3229699a0b2516e93a0a995e9809f6 to your computer and use it in GitHub Desktop.
Save dwelch2344/6c3229699a0b2516e93a0a995e9809f6 to your computer and use it in GitHub Desktop.
test('events', async() => {
const { EventEmitter } = require('events')
const ee = new EventEmitter()
const handler = (breadcrumb: string, delay: number) =>
(promises: Promise<unknown>[]) => {
promises.push(new Promise(resolve => {
setTimeout(() => resolve(breadcrumb), delay)
}))
}
ee.on('thing', handler('a', 0) )
ee.on('thing', handler('b', 100) )
ee.on('thing', handler('c', 0) )
ee.on('thing', handler('d', 3 * 1000) )
const promises: Promise<unknown>[] = []
ee.emit('thing', promises)
console.log({promises}, promises[0] instanceof Promise)
const results = await Promise.all(promises)
console.log({results})
})
@dwelch2344
Copy link
Author

  console.log
    {
      promises: [
        Promise { <pending> },
        Promise { <pending> },
        Promise { <pending> },
        Promise { <pending> }
      ]
    } true
    
    
      console.log
    { results: [ 'a', 'b', 'c', 'd' ] }
    ```

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment