Created
May 7, 2021 09:23
-
-
Save leonidkuznetsov18/71d88c068740f84683644d9492a9ba02 to your computer and use it in GitHub Desktop.
promise from scratch
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 CustomPromise { | |
| state = "PENDING" | |
| value = undefined | |
| thenCallbacks = [] | |
| errorCallbacks = [] | |
| constructor(action) { | |
| action(this.resolver.bind(this), this.reject.bind(this)) | |
| } | |
| resolver(value) { | |
| this.state = "RESOLVED" | |
| this.value = value | |
| this.thenCallbacks.forEach((callback) => { | |
| callback(this.value) | |
| }) | |
| } | |
| reject(value) { | |
| this.state = "REJECTED" | |
| this.value = value | |
| this.errorCallbacks.forEach((callback) => { | |
| callback(this.value) | |
| }) | |
| } | |
| then(callback) { | |
| this.thenCallbacks.push(callback) | |
| return this | |
| } | |
| catch (callback) { | |
| this.errorCallbacks.push(callback) | |
| return this | |
| } | |
| } | |
| let promise = new CustomPromise((resolver, reject) => { | |
| setTimeout(() => { | |
| const rand = Math.ceil(Math.random(1 * 1 + 6) * 6) | |
| if (rand > 2) { | |
| resolver("Success") | |
| } else { | |
| reject("Error") | |
| } | |
| }, 1000) | |
| }) | |
| promise | |
| .then(function(response){ | |
| console.log(response) | |
| }) | |
| .catch(function(error){ | |
| console.log(error) | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment