Skip to content

Instantly share code, notes, and snippets.

@ambergkim
Last active July 4, 2018 01:38
Show Gist options
  • Save ambergkim/bb4f054a612224ddbc3cf5bea08d78ca to your computer and use it in GitHub Desktop.
Save ambergkim/bb4f054a612224ddbc3cf5bea08d78ca to your computer and use it in GitHub Desktop.
JavaScript Callbacks vs Promises
// *******************
// 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);
})
@maxwellred
Copy link

thank you! ill go through this and tinker with my code to get it on par.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment