future.coffee
Simple yet complete implementation of Futures / Promises in CoffeeScript
- Aims to be as simple as possible
- Closely matches the non-deprecated portions of the jQuery 1.9 Deferred API
- Works in a browser environment or as a Node.js module
- Small: 4.4 KB minified, 1 KB gzipped
- No dependencies
Usage
// For Node.js, we must load the module:
// var Future = require('./future');
var computation = new Future();
// Register some completion handlers:
computation.done(function(answer) {
console.log('The computation has succeeded and the answer was: ' + answer);
});
computation.fail(function(reason) {
console.log('The computation has failed because: ' + reason);
});
computation.progress(function(percent) {
console.log('The computation progress is at ' + percent);
});
// Run the computation...
computation.notify('25%');
computation.notify('50%');
computation.notify('75%');
if (Math.random() < 0.5) {
computation.reject('the universe has imploded');
}
else {
computation.notify('100%');
computation.resolve(42);
}
Instead of handing out the Future object to foreign code, you should provide
its promise as a substitute. A promise is a restricted proxy of a Future
that cannot alter its state with resolve or reject, but can be used to add
completion handlers with done, fail, progress, always and then.
....
return computation.promise();
License
MIT.