javascript - Node and async/await, promises … which solution is best? -
working node , express babel , trying figure out best approach between async/await , promises.
key requirements:
- to able pass own error
- not cause blocking
- to approach problem more es6/es7 way
i came out these:
promises:
loadbyidpromises: function (req, res, next, _id) { console.log('loadbyidc: ', _id); artwork.loadbyid( { _id } ) .then( (artwork) => { req.artwork = artwork; next(); }) .catch( (err) => next(new nodataerror('cannot find id'))); }
async/await:
loadbyidasync: async function (req, res, next, _id) { console.log('loadbyidb: ', _id); try { req.artwork = await artwork.loadbyid( { _id } ); next(); } catch (err) { next(new nodataerror('cannot find id')); } }
or async/await wrapper
let wrap = fn => (...args) => fn(...args).catch(args[2]); loadbyidasyncwrap: wrap( async function (req, res, next, _id) { console.log('loadbyida: ', _id); req.artwork = await artwork.loadbyid( { _id } ); next(); }),
promises seems clean may lead cascading when things go complicated. has nice , clean error handling.
async/await seems clean cant figure out how throw error await other way whole try/catch thing.
async/await wrapper seems simple , (at least in case - node express router) handle error (but without possibility set own). wrapper specific req,res,next params , seems me foreign (like divs in html before our css2/3 bliss).
what approach choose? suggestions.
i use promise approach, since async / await
aren't anywhere near mainstream yet.
however see potential problem in invocation of next()
inside initial block meaning have successful first phase, call next()
, if that throws error isn't caught call stack go level, error getting caught first .catch()
block. you'd generating cannot find id
error though real error in next()
handler.
i suggest this, instead:
function (req, res, next, _id) { console.log('loadbyidc: ', _id); artwork.loadbyid( { _id } ) .then((artwork) => req.artwork = artwork) .then(next, (err) => next(new nodataerror('cannot find id'))); }
this still leaves issue on how .catch
exception might thrown next
, @ least won't mislead point @ exception caught.
Comments
Post a Comment