Last active
August 21, 2018 04:54
-
-
Save sj82516/c567616bafc900047eded99622e78a8c to your computer and use it in GitHub Desktop.
implement 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 tPromise { | |
| constructor(fn){ | |
| this.status = "pedding" | |
| this._queue = [] | |
| this._catch = ()=>{ console.error("unhandle tPromise error") } | |
| fn.call(this, this.resolve.bind(this), this.reject.bind(this)) | |
| } | |
| resolve(data){ | |
| this.status = "resolved"; | |
| this.data = data; | |
| if(this._queue.length > 0){ | |
| let task = this._queue.shift(); | |
| let res = task(this.data) | |
| // if respond is tPromise type, then transfer current then queue and catch function to new tPromise | |
| if(typeof res === 'object' && res.__proto__.constructor === tPromise){ | |
| res._queue = this._queue | |
| res._catch = this._catch | |
| return res | |
| } | |
| } | |
| return this | |
| } | |
| reject(error){ | |
| this._catch(error) | |
| this.status = "rejected" | |
| return this; | |
| } | |
| then(fn){ | |
| if(this.status === "resolved"){ | |
| return fn.call(this, this.data) | |
| }else if(this.status === "rejected"){ | |
| this.catch(this.error) | |
| return this | |
| } | |
| // if the promise is resolved in async function. Keep chaining | |
| this._queue.push(fn.bind(this)) | |
| return this | |
| } | |
| catch(fn){ | |
| this._catch = fn.bind(this) | |
| return this | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment