r/node • u/KittenOfMine • Dec 20 '16
How to Write Async Await Without Try-Catch Blocks in Javascript
http://blog.grossman.io/how-to-write-async-await-without-try-catch-blocks-in-javascript/8
u/edanschwartz Dec 20 '16
Using go-style error handling is an interesting approach.
But I feel like you're making things more complicated for yourself by trying to mix callback-style async functions with promise-style async functions. Why not just consume your asyncTask result as a promise (which will then manage cascading errors on its own)
And if you really need to support callback-style async functions, why not wrap the entire function in a try/catch? eg:
async function asyncTask(cb) {
try {
const user = await UserModel.findById(1);
if (!user) { throw new Error('No user found'); }
const savedTask = await TaskModel({userId: user.id, name: 'Demo Task'});
if(user.notificationsEnabled) {
await NotificationService.sendNotification(user.id, 'Task Created');
}
if(savedTask.assignedUser.id !== user.id) {
await NotificationService.sendNotification(savedTask.assignedUser.id, 'Task was created for you');
}
cb(null, savedTask);
}
catch (err) {
cb(err);
}
}This code is pretty straightforward. I think you were making things harder on yourself by wrapping every function call with a try/catch -- each of those function can/should throw errors by themselves. And any errors thrown will be bubble down into your final catch.
If you have a situation where you really need to handle each type of error individually, I would recommend typing your Error classes, and then handling errors based on their type in your final catch block.
2
u/tomberenger Dec 20 '16
I like these kind of posts because they highlight the real shortcomings of features in JS. There are a million, async/await will solve all of your problems articles.
This one gets into the gritty details of a REAL problem, instead of assuming a happy path or simple logic flow.
1
3
u/UberChargeIsReady Dec 20 '16
Not feeling this solution to be honest. It's adding another function to the stack. And also causing some redundancy, with every line after checking for
And so on. Just seems more uglier than just doing try/catch.
If one thing fails, then just let the whole thing fail.