首页 > 解决方案 > 我怎样才能投入 .then 的承诺?

问题描述

我有以下js表达代码:

app.get('/lists2', (req, res) => {
  mongo.getDB()
    .then(db => db.collection('dogs'))
    .then(collection => collection.find().toArray())
    .then(array => res.json(success(array)))
    // How can I throw in the middle of a promise to trigger express's middleware?
    .catch(error => {
      throw {message: "database error"};
    });
});

app.use(function (err, req, res, next) {
  const message = err.message || 'Encountered a server error';
  const status = err.status || 500;
  res.status(status).json({status, message});
})

我已经编写了一个中间件错误处理程序,所以我可以触发一个 API 错误响应,throw问题是我不能扔进去,then因为它在异步代码中,有什么方法可以解决这个问题吗?还是我的错误处理模式不正确?

标签: javascriptnode.jsexpress

解决方案


您应该使用next(参见doc):

app.get('/lists2', (req, res, next) => {
  mongo.getDB()
    .then(db => db.collection('dogs'))
    .then(collection => collection.find().toArray())
    .then(array => res.json(success(array)))
    // How can I throw in the middle of a promise to trigger express's middleware?
    .catch(error => {
      next(new Error("database error"));
    });
});

app.use(function (err, req, res, next) {
  const message = err.message || 'Encountered a server error';
  const status = err.status || 500;
  res.status(status).json({status, message});
})

推荐阅读