Skip to content

Commit

Permalink
feature: add getFirstEvent function (#260)
Browse files Browse the repository at this point in the history
* feature: add getFirstEvent function

* lint

* lint
  • Loading branch information
levivilet authored Dec 27, 2024
1 parent 958d5d2 commit b12a94d
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions packages/preview-process/src/parts/GetFirstEvent/GetFirstEvent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import type { EventEmitter } from 'node:events'
import type { FirstEvent } from '../FirstEvent/FirstEvent.ts'

const addListener = (emitter: EventEmitter, type: string, callback: any): void => {
emitter.on(type, callback)
}

const removeListener = (emitter: EventEmitter, type: string, callback: any): void => {
emitter.off(type, callback)
}

export const getFirstEvent = (eventEmitter: EventEmitter, eventMap: any): Promise<FirstEvent> => {
const { resolve, promise } = Promise.withResolvers<FirstEvent>()
const listenerMap = Object.create(null)
const cleanup = (value: any): void => {
for (const event of Object.keys(eventMap)) {
removeListener(eventEmitter, event, listenerMap[event])
}
resolve(value)
}
for (const [event, type] of Object.entries(eventMap)) {
const listener = (event: any): void => {
cleanup({
type,
event,
})
}
addListener(eventEmitter, event, listener)
listenerMap[event] = listener
}
return promise
}

0 comments on commit b12a94d

Please sign in to comment.