Skip to content

Instantly share code, notes, and snippets.

@supershabam
Created December 3, 2013 00:46
Show Gist options
  • Save supershabam/7761955 to your computer and use it in GitHub Desktop.
Save supershabam/7761955 to your computer and use it in GitHub Desktop.
WorkEmitter
// problem: you need to emit an event and then do something AFTER the handlers have completed
// EventEmitter works ONLY if your event handlers are not async. If you're working in the browser and you
// emit an event and then change page, or submit a form, you run the risk of your async handlers not completing
// before you change pages
// WorkEmitter has the same interface as EventEmitter, except it expects that the handlers will return a promise.
var Q = require('q')
emitter.on('submit', function(form) {
var deferred = Q.defer()
// some async function
form.validate(function(err) {
if (err) {
return deferred.reject(err)
}
deferred.resolve()
})
return deferred.promise
})
emitter.emit('submit', form).then(function() {
// something to do after all events on "submit" have completed successfully
}).fail(function(err) {
// something to do after one or more events on "submit" have errored
}).fin(function() {
// something to do after all events have been processed
})
@supershabam
Copy link
Author

Thinking about adding priorities to this as well.

emitter.on(-1000, 'submit', function() {
  // high priority
})
// normal priority, both will be run in parallel because they share the same priority
emitter.on('submit', function(){})
emitter.on('submit', function(){})
// low priority
emitter.on(9001, 'submit', function(){})

event handler execution flow:

[-1000 handler]
Then
[normal handler, normal handler] (in parallel)
Then
[9001 handler]

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