-
-
Save philipwalton/8402139 to your computer and use it in GitHub Desktop.
// host library code | |
program() | |
.initStuff() | |
.then(function() { | |
dispatcher.emit('beforeRenderPost') | |
}) | |
.then(function() { | |
dispatcher.emit('afterRenderPost') | |
}) | |
.then(function() { | |
dispatcher.emit('beforeWritePost') | |
}) | |
.then(function() { | |
dispatcher.emit('afterWritePost') | |
}) | |
.catch(errorHandler) | |
// now the user's code can simply be the following and the host logic | |
// will wait until their async function is finished before continuing | |
dispatcher.on('beforeRenderPost', doSomethingAsyncToPost) |
need to remind that promises are usually used for actions that should only happen once
True, but if the .emit()
function always returns a new promise instance, this wouldn't be an issue.
However, after giving it more thought I think I'm in agreement with you that events should be one-way communication. They have an established purpose and mixing in this behavior would be unnecessarily confusing.
I think it makes the most sense to create a new paradigm like the one you've outlined. I'll probably work on this for my project and hopefully release it once it's done.
would basically need to check against the expected Function.length to define if you should wait for callback call or not
I originally considered this. Like, if the callback function's .length
property is one greater than the emitter's arguments.length
property, assume async, but that won't work 100% of the time. Sometimes a callback will make use of the arguments object for ...rest
parameter type situations, so it gets a bit hairy.
need to remind that promises are usually used for actions that should only happen once, that's why you probably won't see an implementation of Events that has this kind of feature. - events usually/can happen more than once.