Ivan Drenjanin
Ivan Drenjanin

Reputation: 25

Async/Await while avoiding the Try/Catch block?

I've been working with Node for about month or so and I wanted to utilize the latest features available, like Async/Await style, but I do not like using the try/catch blocks with it. I have been trying to make some kind of a wrapper class and/or functions to wrap the async/await.

I used the destructuring logic of await-to-js npm module to mitigate the usage of try/catch partially, but I am somewhat confused on how would I use it outside of an async function without using es6 promises, and how could I chain multiple awaits using this approach?

Any help, suggestion or critics, if I am doing something completely wrong, is more than appreciated.

Upvotes: 2

Views: 2489

Answers (2)

user3536179
user3536179

Reputation:

A good option to avoid the use of try/catch block in async/await is to create an higher-order function for error handling:

function catchErrors(fn) {
  return function(...args) {
    return fn(...args).catch((err) => {
      console.error(err);
    })
  }
}

async function asyncFunc(name, value) {
  const a = await ...
  const b = await ...
  /* ... */
}

// Wrap it in an higher-order function
const wrappedAsyncFunc = catchErrors(asyncFunc);

wrappedAsyncFunc("lala", 4);

Upvotes: 4

Aminadav Glickshtein
Aminadav Glickshtein

Reputation: 24590

You have to choose. Using try, catch block, or use promises. The reason for async/await exist, is for people who do not like promises, and prefer cleaner code.

If you don't want both, you can use

https://nodejs.org/api/process.html#process_event_uncaughtexception

or

https://nodejs.org/api/process.html#process_event_unhandledrejection

Upvotes: 2

Related Questions