PS: This write-up goes well with node.js or express.js development
We'll go knocking on the try-catch statement door whenever we encounter an asynchronous function in javascript - the traditional way. It is and will always be the backbone to handling async-await functions in server-side development.
It has been of great help when we had to avoid the callback function and got us out of callback hell several times.
But what if we can enhance this and make the try-catch statements shorter and cleaner. Here goes our typical way of handling things.
async function main(req, res, next) {
try {
var result = await doSomething();
console.log(result);
} catch (error) {
console.error(error);
}
}
Being Javascript developers, we are familiar with the above code, result
is printed to the console if everything goes smooth or else error
gets printed - 🍰
A Cleaner Alternative
Say if we're using Express framework and handling requests using try-catch, here's something cleaner and simpler that can be replaced for the never-ending lengthy statements.
const catchAsync = (fn) => (req, res, next) =>{
Promise.resolve(fn(req, res, next)).catch((err) => next(err));
});
catchAsync
function can be considered as a middleware that just accepts the parameters (req, res, next). If there's any error, then it returns the error.
This is how we can call our enhanced error catching function to avoid try-catch statements.
const sampleFunction = catchAsync(async (req, res) => {
const awaitedResponse = await getResponse();
res.send(awaitedResponse);
});
catchAsync
can be called anywhere we need to implement our traditional try-catch logic. Let's keep enhancing our good old lengthy statements and make javascript simpler for budding developers
Top comments (2)
Hmmm... what's different from this between promises or async await?
Does it makes it easier to read? Yes or no?