I am using Q.js
as a promises library. Previously, theres code like:
function X() {
return Q.Promise(function(resolve, reject) {
Users.find()
.then(function(user) {
Q.all([
getUserProfileInfo(user),
getUserSomethingElse(user)
])
.spread(function(profile, something) {
// do stuff
resolve();
})
.catch(function(err) {
// handle error for Q.all()
reject();
})
})
.catch(function(err) {
// handle error for User.find()
reject();
});
});
}
But now I learnt that I can remove the nesting with something like:
function X() {
return Q.Promise(function(resolve, reject) {
return Users.find()
.then(function(user) {
return Q.all([
getUserProfileInfo(user),
getUserSomethingElse(user)
]);
})
.spread(function(profile, something) {
// do stuff
resolve();
})
.catch(function(err) {
// now how do I differenciate between
// the errors from Users.find() and Q.all()?
reject();
});
});
}
The "problem" I have with the bottom (flattened) version is how do I differenciate the errors from Users.find()
and Q.all()
? Or in general possibly many other errors in the long then
chain?
Currently I might use something like
function(err) {
if (err.errors && err.statusCode) {
// do something
} else if (err.message) {
// do something
}
}
But this is not really "nice" code isit? There must be a better way?