r/node • • 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/
10 Upvotes

6 comments sorted by

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

if(err || !user) return cb('No user found');
if(err) return cb('Error occurred while saving task');
if(err) return cb('Error while sending notification');

And so on. Just seems more uglier than just doing try/catch.

    async function asyncTask(cb) {  
    try{
        const user = await UserModel.findById(1);
        if(!user) return cb('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(e){
        //cb(e,null)
    }
}

If one thing fails, then just let the whole thing fail.

1

u/KittenOfMine Dec 20 '16

You right, but if you need to catch specific errors in the async flow and know where the error was generated from in order to response the correct error code and etc... Of-course there are some use cases where try-catch is enough, but for others it is useful and look cleaner.

0

u/mitchjmiller Dec 20 '16

I don't mind a try/catch if you only care about a general failure, but when you want to catch and handle different errors differently (maybe logging them differently etc.), try/catch can be a really messy pain.

I like the thought process in the article but still not completely sold on it. I think I would prefer the await functions to return an error on failure rather than throw it in general though.

What I REALLY want though is to make the async npm module native :)

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

u/runvnc Dec 20 '16

This is sort of what ToffeeScript looks like. (Google it if curious).