我试图在 app.get 函数内部使用一个 Promise,该函数将运行一个基于 Promise 运行的查询。但问题是响应不会等待承诺而只是响应。

知道代码应该如何让承诺可以存在于 Express 应用程序的 app.get 中吗?

有帮助吗?

解决方案

app.get('/test', function (req, res) {
    db.getData()
    .then(function (data) {
        res.setHeader('Content-Type', 'text/plain');
        res.end(data);
    })
    .catch(function (e) {
        res.status(500, {
            error: e
        });
    });
});
.

其他提示

这是来自 快速文档:

app.get('/', function (req, res, next) {
  // do some sync stuff
  queryDb()
  .then(function (data) {
    // handle data
    return makeCsv(data)
  })
  .then(function (csv) {
    // handle csv
  })
  .catch(next)
})

app.use(function (err, req, res, next) {
  // handle error
})

值得注意的主要是通过 next 通过 .catch() 以便公共错误处理路由可以封装下游的错误处理逻辑。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top