DEV Community

Discussion on: Better error handling with async/await

Collapse
 
infinity1975 profile image
Robert Larsson • Edited

Why not only do this?

async function userProfile() {
  const user = await getUser().catch(() => throw Error('Could not fetch user details');

  const friendsOfUser = await getFriendsOfUser(user.userId).catch(() => throw Error('Could not fetch user\'s friends');

  const posts = await getUsersPosts(user.userId).catch(() => throw Error('Could not fetch user\'s posts'));

  showUserProfilePage(user, friendsOfUser, posts);
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
sobiodarlington profile image
Sobio Darlington • Edited

Why not only do this?

I'm not clear with this, but you could throw inside of .catch to propagate it if you like.

Your example has syntax error though.

Collapse
 
infinity1975 profile image
Comment marked as low quality/non-constructive by the community. View Code of Conduct
Robert Larsson • Edited

Complaining about syntax error is just really showing how little you want to take in what people say. The solution is what you do, but less complicated. And your idead is stolen from another guy who also commented here. And by the way, your solution don't have a userId so :)

Thread Thread
 
sobiodarlington profile image
Sobio Darlington • Edited

Sorry if my response came off that way. We have lots of beginners that might copy your example and not know why it's not working, that was why I pointed out the syntax error(It was unnecessary).

I didn't steal my post from that guy.

I got my handle function solution from a youtuber, which I linked to his article at the end of my post. I also linked an npm package "await-to" that did similar implementation.
If you want to accuse me of stealing, you should at least be correct with the origin of my solution.

Original source of my solution

Also I've been writing JavaScript for 8years, I don't need to steal a post to write about Promises/asynchronous JavaScript.

Collapse
 
abernier profile image
abernier

using throw inside .catch is the way to go to stop execution of the function. It's like our old if (err) return; ❤️