Created
June 28, 2022 18:59
-
-
Save geekyorion/4ca54e1ac291507ac5f8504dcce55275 to your computer and use it in GitHub Desktop.
Promise with callback for success and error functions
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
| const getValue = (value, successFn, errorFn) => { | |
| new Promise((res, rej) => { | |
| if (value > 100) { | |
| res(value * 2); | |
| } else { | |
| rej(value / 2); | |
| } | |
| }) | |
| .then(data => { | |
| successFn(data); | |
| }) | |
| .catch(errData => { | |
| errorFn(errData); | |
| }); | |
| }; | |
| const evaluate = () => { | |
| const randomNumber = ~~(Math.random() * 200); | |
| getValue( | |
| randomNumber, | |
| (data) => console.log(data), | |
| (err) => { | |
| throw new Error(`since value (value: ${randomNumber}) is less than 100, we are getting half of it: ${err}`); | |
| }, | |
| ); | |
| } | |
| evaluate(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment