This library is a light and dead simple Promises implementation following a well-structured OOP pattern.
I hope to create a compliant with the Promises/A+ specification. If you find an error or fault please report it and will be corrected in the shortest possible time.
To use the library simply include the file with the class:
<script src="js/Promise.js"></script>
Now you can create a promise instance:
var promise = new Promise(function (resolve, reject) {
// some asynchronous task here
// resolve(someValue); If the task was performed successfully
// reject('some reason'); If the task failed
});
var promise = new Promise(function(resolve, reject) {
setTimeout(function () {
var probability = Math.floor((Math.random()*10) + 1);
if (probability < 6) {
resolve(1);
} else {
reject('Bad luck. The probability was ' + probability);
}
}, 1000);
});
var messages = document.querySelector('#messages');
promise.then(function (val) {
console.log(val); // 1
return val + 2;
}).then(function (val) {
console.log(val); // 3
return val + 2;
}).then(function (val) {
console.log(val); // 5
return val;
}).fail(function (reason) {
console.log('Fail: %s', reason);
}).done(function (value) {
console.log('All process is done. Result: %s', value);
});
This creates and returns a new promise, resolver
must be a function; the resolver
function is passed two arguments:
resolve
: Should be called with a single argument. If it is called with a non-promise value then the promise is fulfilled with that value. If it is called with a promise (A) then the returned promise takes on the state of that new promise (A).reject
: Should be called with a single argument. The returned promise will be rejected with that argument.
These methods are invoked on a promise instance by calling promise.methodName
Add handlers to be called when the Promise object is resolved
Add handlers to be called when the Promise object is rejected.
Determine whether a Promise object has been rejected.
Determine whether a Promise object has been resolved.
Add handlers to be called when the Promise object is resolved, rejected.
These methods are invoked by calling Promise.methodName
.
Return a rejected Promise object with a given reason.
Return a Resolved Promise object with a given value.