Nur Rony
Polyglot Programmer, DevOps and Forever Learner

Remove Ugly try/catch blocks in async/await

Remove Ugly try/catch blocks in async/await

Asynchronous programming in Javascript can be tricky and ugly with callback and even with Promise (afterall, we pass callbacks in then ?). Fortunately we have async/await keyword which make asynchronous programming looks like synchronous but if you ommit try/catch, it won't yell if any error occrred. But this become more ugly soon wrapping code in nested try/catch. To get rid of it, try this cool tricks

async function helloWorld() {

    op1result = await asyncOperationOne(param1),
    op2result = await asyncOperationTwo(op1result),
    op3result = await asyncOperationThree(op2result);

  return op3result;

// higher-order function to catch errors
const catchErrors = asyncFns => (...args) => asyncFns(...args).catch(console.error);

(async () => {
  await catchErrors(helloWorld)();

Credit: Thanks @WesBos