No more try.....catch
Hey, ๐ how are you ?
Are you a back-end developer, handling multiple database operations & tasks or having custom promises written or has a service which returns a promise, and you have to handle it using the ugly try..catch block which might have one block containing several lines of code ? ๐ค
Solution ๐
There is a npm module available which reduces complexity and introduces better readability just as if it's all synchronous in nature. It's called await-to-js. ๐
It's an async await wrapper which focuses on making the task of error handling easier. The output from the function is a de-structured output with error
and data
, which can be further used independently.
Usage โ๏ธ
const to = require('await-to-js').default;
const getNotificationToken = async (userId) => {
const [err, token] = await to(redis.get(userId))
if (err) {
// Handle your error
}
return token
}
This is a simple function which returns a token
from redis
for a particular user.
My Thoughts ๐ญ
One should consider this to get started with less bugs while handling promises.
Signing off... โ๏ธ