This website collects cookies to deliver better user experience
Migrating from promise chains to async-await and escaping the try catch hell
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.
functionhell(){step1((a)=>{step2((b)=>{step3((c)=>{// some code ...})})})}
The above code can be written in a clean line-by-line format using async-await.
asyncfunctionheaven(){const a=awaitstep1();const b=awaitstep2(a);const c=awaitstep3(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.
asyncfunctiontowerOfTerror(){let a;let b;let c;try{ a=awaitstep1();}catch(error){handle(error);}try{ b=awaitstep2(a);}catch(error){handle(error);}try{ c=awaitstep3(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.
awaitstep1().catch(fun);
But that can still get repetitive.
asyncfunctiongetBetter(){const a=awaitstep1().catch(err=>handler(err);const b=awaitstep2(a).catch(err=>handler(err);const c=awaitstep3(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.
Now you can call this function in your code you can de-structure it to get a clean one-liner error handling.
asyncfunctionmain(){const[data,error]=awaitawesome();const[data2,error2]=awaitawesome();//or use the if statement if you want to handle the error differentlyif(error){//do something}}