Last active
July 4, 2018 01:38
-
-
Save ambergkim/bb4f054a612224ddbc3cf5bea08d78ca to your computer and use it in GitHub Desktop.
JavaScript Callbacks vs Promises
This file contains 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 | |
// ******************* | |
function getDataCallback(data) { | |
// do something with the new data data | |
} | |
function getData(callback) { | |
// getting the data | |
// send the data through the callback | |
callback(data) | |
} | |
getData(getDataCallback); | |
// ******************************* | |
// Promise example using mongoose | |
// ******************************* | |
//save a new book to the database | |
newBook.save() | |
.then(() => { | |
// query the database for all of the books | |
return Books.find({}); | |
}) | |
.then(books => { | |
//do something with all the books | |
}) | |
.catch(err => { | |
console.error(err); | |
}) | |
// *********************************** | |
// NOT recommended way to use promises | |
// ************************************ | |
// This is trying to use promises like you use callbacks and defeats the purpose of promises, still putting you in 'callback hell' | |
// Also not DRY | |
newBook.save() | |
.then(() => { | |
Books.find({}) | |
.then(books => { | |
// do something with the books. | |
}) | |
.catch(err => { | |
console.error(err); | |
}) | |
}).catch(err => { | |
console.error(err); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thank you! ill go through this and tinker with my code to get it on par.