绑定函数中包含Async/await错误

Async/await errors being swallowed in bound function

本文关键字:await 错误 Async 包含 函数 绑定      更新时间:2023-09-26

我正在运行一个使用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中包装addItemFromDBremoveItemFromDB函数,所以我将其包装在辅助函数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)
  }
}

但是,addItemFromDBremoveItemFromDB中发生的所有错误都被静默地吞下。我所发现的是,当我删除.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参数。