Last active
August 29, 2015 14:23
-
-
Save mlms13/94888406c082195ee8d6 to your computer and use it in GitHub Desktop.
A promise library for professionals.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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