如何使用Express app中的promises?

sam*_*miq 13 node.js promise express parse-platform

我试图在app.get函数中使用一个promise,它将运行一个将在promise上运行的查询.但问题是响应不等待承诺而只是回应.

任何想法代码应该如何承诺可以在快递应用程序中的app.get内生活?

Esa*_*ija 23

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
        });
    });
});
Run Code Online (Sandbox Code Playgroud)


Poi*_*Oak 5

以下是Express文档的答案:

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
})
Run Code Online (Sandbox Code Playgroud)

值得注意的是主要用于传递next,.catch()以便常见的错误处理路由可以将错误处理逻辑封装在下游.