@railzai/bottleneck
Version:
Distributed task scheduler and rate limiter
39 lines (37 loc) • 1.44 kB
text/coffeescript
class Events
constructor: ( ) ->
= {}
if .on? or .once? or .removeAllListeners?
throw new Error "An Emitter already exists for this object"
.on = (name, cb) => name, "many", cb
.once = (name, cb) => name, "once", cb
.removeAllListeners = (name=null) =>
if name? then delete [name] else = {}
_addListener: (name, status, cb) ->
[name] ?= []
[name].push {cb, status}
listenerCount: (name) ->
if [name]? then [name].length else 0
trigger: (name, args...) ->
try
if name != "debug" then "debug", "Event triggered: #{name}", args
return unless [name]?
[name] = [name].filter (listener) -> listener.status != "none"
promises = [name].map (listener) =>
return if listener.status == "none"
if listener.status == "once" then listener.status = "none"
try
returned = listener.cb?(args...)
if typeof returned?.then == "function"
await returned
else
returned
catch e
if "name" != "error" then "error", e
null
(await Promise.all promises).find (x) -> x?
catch e
if "name" != "error" then "error", e
null
module.exports = Events