Saturday, 20 June 2020

Understanding async wrapper in Nodejs

I am trying to understand a better way to do error handling in Nodejs. I was following thisreally well written article. However, there is one thing that I do not understand.​app.post('/signup', async(req, res, next) => { try { await firstThing() await secondThing() } catch (error) { return next(error) } }) The author states that add try catch on every single route is cumbersome which I agree with. He then says that we can change it to something like this:app.post('/signup', async(req, res, next) => { function runAsync () { await firstThing() await secondThing() } runAsync() .catch(next) }) And finally he says we can turn it to something like this:function runAsyncWrapper (callback) { return function (req, res, next) { callback(req, res, next) .catch(next) } } app.post('/signup', runAsyncWrapper(async(req, res) => { await firstThing() await secondThing() }) I understand that we are passing the entire function to callback so​callback = async(req, res) => { await firstThing() await secondThing() } ​What we return isfunction (req, res, next) { callback(req, res, next) .catch(next) } Which now becomes:function (req, res, next) { async(req, res,next) => { await firstThing() await secondThing() .catch(next) } } So this wrapperapp.post('/signup', runAsyncWrapper(async(req, res) => { await firstThing() await secondThing() }) Finally becomesapp.post('/signup', function (req, res, next) { async(req, res,next) => { await firstThing() await secondThing() .catch(next) } }) What is the purpose of having 2 (req,res,next) ?

Submitted June 20, 2020 at 05:03PM by sahilgreen

No comments:

Post a Comment