asynchronous/等待错误在绑定函数中被吞噬
我正在运行使用async / await的Express应用程序。
我有两条看起来像这样的路线:
app.post('/add-item', item.bind(null, 'add')) app.post('/remove-item', item.bind(null, 'remove'))
路由处理程序定义如下:
async function item (action, req, res, next) { if (action === 'add') { var result = await addItemFromDB() res.json(result) } else { var result = await removeItemFromDB() res.json(result) } }
因为我想避免在try/catch
包装addItemFromDB
和removeItemFromDB
函数,所以将其包装在助手函数asyncRequest
:
asyncRequest(async function item(req, res, next) { if (action === 'add') { var result = await addItemFromDB() res.json(result) } else { var result = await removeItemFromDB() res.json(result) } })
将asyncRequest
定义为:
function asyncRequest (handler) { return function (req, res, next) { return handler(req, res, next).catch(next) } }
但是, addItemFromDB
和removeItemFromDB
中发生的所有错误都会被悄悄吞下。 我发现的是,当我删除.bind(null, 'add')
等一切正常工作。
任何想法,为什么这是这种情况?
你将不得不使用
app.post('/add-item', asyncRequest(item.bind(null, 'add'))); app.post('/remove-item', asyncRequest(item.bind(null, 'remove)));
可能你试图在你的自定义item
函数上调用asyncRequest
,这个函数需要4个参数,这不是asyncRequest
函数对于handler
参数的期望。