I'm trying to figure out how to use promises correctly with the bluebird library. I've come across some nested promises in my code and I noticed that in the bluebird docs it reads:
if you are utilizing the full bluebird API offering, you will almost never need to resort to nesting promises in the first place.
There are many other blog posts about promises being misused and nesting is a regular anti-pattern.
loadCar(someUri) // jqXHR
.then(function (car) {
if (carHasFourDoors(car)) {
loadMake(car.make)
.then(function (make) {
loadModel(make.model)
.then(function (model) {
loadCarDetails(model)
});
});
}
else if (carHasTwoDoors(car)) {
loadModel(make.model)
.then(function (model) {
loadCarDetails(model)
});
}
});
All of my functions return objects. Looking at the bluebird docs, it seems like there are multiple helper methods: all(), join(), props().
So, my question is: How could I avoid the nesting if there are dependencies? Perhaps this is my misunderstanding of the asynchronous nature of promises. Could something like this work?
Promise.all(loadCar(someUri), loadMake(car.make), loadModel(make.model))
.then(function(car, make, model) {
// do logic
});