Created
June 19, 2015 04:54
-
-
Save alkhe/d512a012b12787516726 to your computer and use it in GitHub Desktop.
Five-Minute Promise Implementation
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
let a = new Prom((reject, resolve) => { | |
setTimeout(() => resolve('Promise A'), 1000); | |
}).then(result => { | |
console.log(result); | |
}); | |
let b = new Prom((reject, resolve) => { | |
resolve('Promise B'); | |
}).then(result => { | |
console.log(result); | |
}); |
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
class Prom { | |
constructor(fn) { | |
this.resolved = false; | |
this.rejected = false; | |
this.result = null; | |
this.thenHandlers = []; | |
this.failHandlers = []; | |
let resolve = result => { | |
this.resolved = true; | |
this.result = result; | |
this.thenHandlers.forEach(fn => fn(result)); | |
}; | |
let reject = result => { | |
this.rejected = true; | |
this.result = result; | |
this.failHandlers.forEach(fn => fn(result)); | |
}; | |
fn(reject, resolve); | |
} | |
then(fn) { | |
if (this.resolved) { | |
fn(this.result); | |
} else { | |
this.thenHandlers.push(fn); | |
} | |
return this; | |
} | |
fail(fn) { | |
if (this.rejected) { | |
fn(this.result); | |
} else { | |
this.failHandlers.push(fn); | |
} | |
return this; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment