I am having a bit of trouble flattening out my promises as an alternative to nesting.
Suppose I want to make a table join by retrieving a user and using its id to retrieve associated posts in another table. Like so.
User.get(uid)
.then(usr => {
return Post.get(usr.id)
})
.then(posts => {
//send posts or continue the promise chain
});
Now the issue arises whenever I want to execute error handling logic that is specific to a certain promise and not execute anything else. In my example if the DB doesn't find a user with that ID it throws an error, and then if it doesn't find posts by the given foreign key it will also throw an error. What I would like to do is to respond with an error specific message like 'user was not found' or 'posts were not found given the user', etc.
I tried to do this
User.get(uid)
.catch(e => {
//This executes whenever a user is not found but the problem is that it also
//executes the following 'then' statement
})
.then(usr => {
return Post.get(usr.id)
})
.then(posts => {
//send posts or continue the promise chain
})
.catch(e => {
//This should only execute when posts aren't found with the id
});
Now the previous code did not work since the .then
executes regardless of an error.
So I thought about removing all .then statements after catch statements, like this
User.get(uid)
.then(usr => {
return Post.get(usr.id)
})
.then(posts => {
//send posts or continue the promise chain
})
.catch(e => {
//This executes whenever a user is not found but the problem is that it also
//executes the following 'then' statement
})
.catch(e => {
//This should only execute when posts aren't found with the id
});
But this doesn't work since the first .catch statement always executes.
In a synchronous fashion this would be the way my code would be written
try
{
var user = getUser(id);
try
{
var posts = getPosts(user.id);
}
catch(e)
{
//this executes only if posts aren't found
}
}
catch (e)
{
//this executes if the error originates from obtaining a user
}