Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 26, 2021 04:22 pm GMT

Migrating from promise chains to async-await and escaping the try catch hell

async ()=> {await promise}

async-await is a life saver when it comes to avoiding callback hell or the pyramid of doom.

function hell(){step1((a)=>{  step2((b)=>{    step3((c)=>{       // some code ...         })       })     })}

The above code can be written in a clean line-by-line format using async-await.

async function heaven(){   const a= await step1();   const b= await step2(a);   const c= await step3(b);   return a + b + c;}

This is great but when it comes to error handling this simplicity again goes for a toss because you end up with a try-catch tower of terror.

async function towerOfTerror(){let a;let b;let c;try{ a=await step1();} catch(error){ handle(error);}try{ b=await step2(a);} catch(error){ handle(error);}try{ c=await step3(b);} catch(error){ handle(error);}return a + b + c;}

All your one-liners have now expanded to at least 5 lines of code.
One easy way out would be to append the catch method to the end of each promise.

await step1().catch(fun);

But that can still get repetitive.

async function getBetter(){   const a= await step1().catch(err=>handler(err);   const b= await step2(a).catch(err=>handler(err);   const c= await step3(b).catch(err=>handler(err);   return a + b + c;}

Another option is to create a function that implements one try-catch to replace all the others. It will first resolve the promise and then return an array that has the first element as the data and the second element as an error. But if there is an error then the data is null and the error is defined.

async function awesome(){ try{  const data=await promise;  return [data,null]; } catch(error){  console.error(error);  return [null,error]; }

Now you can call this function in your code you can de-structure it to get a clean one-liner error handling.

async function main(){ const[data,error]=await awesome(); const[data2,error2]=await awesome();//or use the if statement if you want to handle the error differentlyif(error){   //do something   }}

Original Link: https://dev.to/avishkardalvi/migrating-from-promise-chains-to-async-await-and-escaping-the-try-catch-hell-191l

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To