Skip to content

Instantly share code, notes, and snippets.

@mlms13
Last active August 29, 2015 14:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mlms13/94888406c082195ee8d6 to your computer and use it in GitHub Desktop.
Save mlms13/94888406c082195ee8d6 to your computer and use it in GitHub Desktop.
A promise library for professionals.
function Pro(callback) {
this.isResolved;
this.isRejected;
this.thens = [];
this.catches = [];
var resolve = function (data) {
if (this.isResolved || this.isRejected) return;
this.thens.forEach(function (fn) {
fn(data);
});
this.isResolved = true;
}.bind(this);
var reject = function (error) {
if (this.isResolved || this.isRejected) return;
this.catches.forEach(function (fn) {
fn(error);
});
this.isRejected = true;
}.bind(this);
callback(resolve, reject);
}
Pro.prototype.then = function (fn) {
if (this.isResolved) {
fn('oops, we lost ur data');
} else {
this.thens.push(fn);
}
return this;
};
Pro.prototype.catch = function (fn) {
if (this.isRejected) {
fn(new Error('sorry, you missed your chance'));
} else {
this.catches.push(fn);
}
return this;
};
// usage:
var promise = new Pro(function (resolve, reject) {
if (Math.random() < 0.333333) {
reject(new Error('1 in 3! Explosion!'));
}
window.setTimeout(function () {
resolve(1);
}, 2000);
});
promise
.then(function (data) {
console.log('resolved with data:', data);
})
.catch(function (err) {
console.error(err.message);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment