首页 > 解决方案 > 异步/等待发布请求 - nodejs

问题描述

在继续我的 POST 请求的其余部分之前,我需要进行数据库调用并等待它的响应(在这种情况下等待承诺被履行)。

app.post("/charge", (req, res) => {
  var user_stripe_id = await queries.get_stripe_id_by_email(req.body.token.email);
}

但是我不能等待查询,因为我不在异步函数中。我怎样才能使app.post异步?

在其他路线中,我已经这样做了

app.get('/', async function (req, res) {
  const leagues = await distinctLeagues();
  res.render('home', { leagues: leagues });
});

但我想知道如何使用箭头函数语法来做到这一点。

标签: node.jsexpress

解决方案


你可以在 es6 中创建一个async函数,如下所示:

app.post("/charge", async (req, res) => {
  var user_stripe_id = await queries.get_stripe_id_by_email(req.body.token.email);
}

这是 async-await 的理想用法,在 try-catch 中使用它。由 Promise 解析的值将被分配给quote,如果 Promise 被拒绝,则将执行 catch 块。

async function main() {
  try {
    var quote = await getQuote();
    console.log(quote);
  } catch (error) {
    console.error(error);
  }
}

推荐阅读