Promiser
promiser
is a simple manager of deferreds by name. Rather than creating and maintaining references to jQuery.Deferred
objects, simply register a handler by name and resolve or reject it by name.
promiser.done('test', function() {
console.log('hello world');
});
promiser.resolve('test');
promiser.isResolved('test');
The promiser API includes all the methods on the jQuery Deferred object.
Chaining works as expected:
promiser
.done('test1', function() { ... })
.done('test2', function() { ... })
.done('test3', function() { ... });
For a more elegant approach, an object can be passed:
promiser.done({
test1: function() { ... },
test2: function() { ... },
test3: function() { ... }
});
It supports the when
method:
promiser.when('test1', 'test2', 'test3', function() {
console.log('all done!');
});
Promiser can manage other deferred for you:
promiser.manage('ajax', $.ajax({ ... }));
It can also stop managing a deferred:
var xhr = promiser.unmanage('ajax');
You can even reset a deferred. This provides a clean alternative to passing around references to deferred objects:
promiser.reset('test1');
Deferreds can be watched for when they are initially created. This makes it easy to only execute something if another object needs it:
promiser.watch('lazy-data', function() {
$.ajax({
success: function(data) {
promiser.resolve('lazy-data', data);
},
error: function(xhr, text, err) {
promiser.reject('lazy-data', xhr, text, err);
}
});
});
promiser.done('lazy-data', function(data) {
});
Install
Bower
bower install promiser
NPM
npm install promiser
Setup
promiser.js works in the browser as well as the Node and AMD environments.
Usage
The promiser
object can be used three ways:
Singleton
promiser.done('foo', function() { ... });
Constructor
var p1 = new promiser;
p1 instanceof promiser;
Function
var p1 = promiser();
var p2 = promiser({});