-
-
Save isavch/4ad8190b50d72e40821c0087eef92b42 to your computer and use it in GitHub Desktop.
promise
This file contains hidden or 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 MyPromise { | |
| constructor(handler) { | |
| this.status = 'pending'; | |
| if (!handler) { | |
| throw new TypeError('Promise resolver is undefined'); | |
| } | |
| handler(value => { | |
| this.value = value; | |
| }, error => { | |
| this.value = error; | |
| }) | |
| } | |
| then(succCb, errorCb) { | |
| try { | |
| this.value = succCb(this.value); | |
| this.status = 'resolved'; | |
| } catch(error) { | |
| this.status = 'rejected'; | |
| if(errorCb) { | |
| this.value = errorCb(error); | |
| } else { | |
| this.value = error; | |
| } | |
| return this; | |
| } | |
| return this; | |
| } | |
| catch(errorCb) { | |
| if (errorCb && this.status === 'rejected') { | |
| this.value = errorCb(this.value); | |
| } | |
| return this | |
| } | |
| } | |
| var a = new MyPromise((resolve, reject) => { | |
| resolve(1); | |
| }); | |
| a.then(s => { | |
| console.log(s); | |
| return 4; | |
| }) | |
| .then(d => { | |
| console.log(d); | |
| throw 3; | |
| }) | |
| .catch(e => { | |
| console.log(e, 'catch'); | |
| return 5; | |
| }).then(p => console.log(p)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment