Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialFernando Balandran
492 PointsSurely there has to be a better way to handle callbacks?
When you cleaned the three saves with the create method, and cleaned that a bit. You said ok looks much better and honestly it still looked like a complete mess to my python and java eyes. It is quite hard to track opening and closing braces in all those nested callbacks.
With that being said, I haven't done much programming in javascript, please tell me there is a better way to handle callbacks course was going pretty good for me until I saw the callback hell.
2 Answers
Brett Carter
Full Stack JavaScript Techdegree Graduate 17,766 PointsI wrote this with promises for anyone who is interested.
Note that the findSameColor
static method does not take a callback parameter which using promises.
findSameColor
without callback:
AnimalSchema.methods.findSameColor = function() {
return this.model('Animal').find({color: this.color});
}
Promise chain (not perfect, but much better):
Animal.remove({})
.then(_ => {return Animal.create(animalData)})
.then(_ => {return Animal.findOne({type: 'elephant'});})
.then(elephant => {return elephant.findSameColor();})
.then((coloredAnimals) =>{
return coloredAnimals.forEach(animal => {
console.log(`${animal.name} the ${animal.color} is a ${animal.size} ${animal.type}`);
});
})
.then(_ => db.close(_ => console.log('db connection closed')))
.catch(err => console.log(err));
});
Would be cleaner with async/await, which Mongo 5 now supports natively.
Clayton Perszyk
Treehouse Moderator 48,850 PointsLook into Promises, async/await:
Fernando Balandran
492 PointsThanks! That's exactly what I was looking for. Promises are much better.
Fernando Balandran
492 PointsFernando Balandran
492 PointsThat looks much cleaner and more readable. Thanks Brett!