Created
January 14, 2019 15:09
-
-
Save rgabs/44ac0ac4b4bce61e08e1edc4dac3a2e2 to your computer and use it in GitHub Desktop.
A custom implementation of Promises using callbacks.
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
| // Callback version of the async task | |
| const someApi = (url, onSuccess, onError) => { | |
| setTimeout(() => { | |
| url === "someURL" ? onSuccess("success") : onError("some error"); | |
| }); | |
| }; | |
| someApi( | |
| "someURL", | |
| status => console.log("success bro", status), | |
| errMessage => console.log("failed bro", errMessage) | |
| ); | |
| // Promisified version of the async task | |
| function someApiPromisified(url) { | |
| this.successHandlers = []; | |
| this.then = onSuccess => { | |
| this.successHandlers.push(onSuccess); | |
| return this; | |
| }; | |
| const executeSuccessHandlers = payload => { | |
| let lastOutput = payload; | |
| this.successHandlers.forEach(handler => { | |
| lastOutput = handler(lastOutput); | |
| }); | |
| }; | |
| this.catch = onError => (this.onError = onError); | |
| setTimeout(() => { | |
| return url === "someURL" | |
| ? executeSuccessHandlers("success") | |
| : this.onError("some error"); | |
| }, 2000); | |
| } | |
| new someApiPromisified("someURL") | |
| .then(status => { | |
| console.log("status", status); | |
| return status; | |
| }) | |
| .then(console.log); | |
| new someApiPromisified("somethingElse").catch(status => { | |
| console.log("Error occured.", status); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment