Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save maxwellred/cde5b5c670cccd2bbb1649dde2e023f4 to your computer and use it in GitHub Desktop.
Save maxwellred/cde5b5c670cccd2bbb1649dde2e023f4 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);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment