How to Avoid Async Try-Catch Hell
- By : Mydatahack
- Category : Node.js, Web Technologies
- Tags: Async, JavaScript
This post is based on this excellent short youtube video..
Let’s see async try-catch hell. If we do try-catch on every single async function, it creates a tower of terror. Welcome to try-catch hell.
async function towerOfTerror() { let a; let b; let c; try { a = await step1(); } catch (e) { handle(e); } try { b = await step2(); } catch (e) { handle(e); } try { c = await step3(); } catch (e) { handle(e); } }
There are two ways we can avoid this.
First of all, we can just catch the error by chaining it.
async function useCatch() { const a = await step1().catch(e => handle(e)); const b = await step1().catch(e => handle(e)); const c = await step1().catch(e => handle(e)); return a + b + c; }
Alternatively, in the async function we use, we can return an array of data and error.
async function handleTryCatch() { try { const data = await promise; return [data, null]; } catch (e) { console.error(e); return [null, e]; } } async function handleTryCatch2() { try { const data = await promise; return [data, null]; } catch (e) { console.error(e); return [null, e]; } } async function main() { const [data, error] = await handleTryCatch(); if (error) { // can do action here. } const [data2, error2] = await handleTryCatch2(); const [data3, error3] = await handleTryCatch3(); }
Amazing!