The Await Catch Pattern
See Also:
See https://github.com/therootcompany/async-router
Async / Await is Ugly
try {
let results;
try {
results = await ProfileModel.get(req.user.id);
} catch (err) {
if ("E_NO_RECORD" !== err.code) {
throw err;
}
results = Profile.create();
}
res.json(await doStuff(results));
} catch (e) {
next(err);
}
Promise Chains are Clean
return ProfileModel.get(req.user.id)
.catch(function (err) {
if ("E_NO_RECORD" !== err.code) {
throw err;
}
return Profile.create();
})
.then(function (results) {
return doStuff(results).then(res.json);
})
.catch(next);
Await Catch is Elegant
let results = await ProfileModel.get(req.user.id)
.catch(function (err) {
if ("E_NO_RECORD" !== err.code) {
throw err;
}
return Profile.create();
});
res.json(await doStuff(results));
@jsmart523: Yes, and no. You could swap
for
But try/catch is a nasty code smell... about as bad as the sulfur burps I'm having today... yuck!
Take a look here, and never try / catch in express routes again:
https://github.com/therootcompany/async-router