A tiny deferred object constructor
Does what it says on the tin and does it well. That is all.
The only events are
var def =doneconsole.log'Great success!';failconsole.log'Dang.';alwaysconsole.log'Always clean up after yourself.';;
Once an instance has been resolved or rejected, it can't be resolved or rejected again. However, adding a
always callback to a rejected object will result in the callback function being called immediately with the expected arguments and context.
defresolvemessage: 'Very important message.';// Many lines of code later...defdoneconsole.logresponsemessage; // Logs 'Very important message' immediately.failconsole.logresponse.error; // Will never be called. In fact, the callback is discarded immediately.alwaysconsole.log'All over.'; // Called immediately after the done callback above.;
Returning any kind of value (null included) from a callback will cause that value to be passed as the first argument to subsequent callbacks. This feature allows us to create an interesting onion-skin pattern, morphing data as it passes through the layers of callbacks.
defdonereturn templateEnginerender'my-template' response;;// Many lines of code later...defdonedocumentbodyinnerHTML = html;;
Context can be supplied to callbacks by calling the
rejectWith methods. The context is the same for all callbacks, even those added and fired after resolution or rejection.
donethis.logmessage; // Logs 'Hai' to the console.resolveWithconsole 'Hai';
Arrays of functions may be passed to the callback methods.