Skip to content

Instantly share code, notes, and snippets.

@r3dm1ke
Last active August 14, 2020 08:01
Show Gist options
  • Select an option

  • Save r3dm1ke/859be580594c46223d120438a3cb5a8a to your computer and use it in GitHub Desktop.

Select an option

Save r3dm1ke/859be580594c46223d120438a3cb5a8a to your computer and use it in GitHub Desktop.
Converting a callback into a Promise
// 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);
}
@jstirnaman

Copy link
Copy Markdown

Typo "functoin" on line 28. I enjoyed reading https://everyday.codes/javascript/10-javascript-interview-questions-for-2020/. Thanks

@r3dm1ke

r3dm1ke commented Jun 29, 2020

Copy link
Copy Markdown
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