Last active
August 14, 2020 08:01
-
-
Save r3dm1ke/859be580594c46223d120438a3cb5a8a to your computer and use it in GitHub Desktop.
Converting a callback into a 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
| // the function itself | |
| function getData(callback, errorCallback) { | |
| try { | |
| // Do some network/api stuff... | |
| callback(result) | |
| } catch (e) { | |
| errorCallback(e); | |
| } | |
| } | |
| // Here is how you would use it: | |
| getData(result => console.log(result), error => console.error(error)); | |
| // Here is how to create a Promise-based function from it: | |
| function getDataAsync() { | |
| return new Promise((resolve, reject) => { | |
| getData(resolve, reject); | |
| }); | |
| } | |
| getDataAsync() | |
| .then(result => console.log(result)) | |
| .catch(error => console.error(error)); | |
| // OR | |
| async function main() { | |
| const result = await getDataAsync(); | |
| console.log(result); | |
| } |
Author
Typo "functoin" on line 28. I enjoyed reading https://everyday.codes/javascript/10-javascript-interview-questions-for-2020/. Thanks
Thank you!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Typo "functoin" on line 28. I enjoyed reading https://everyday.codes/javascript/10-javascript-interview-questions-for-2020/. Thanks