await仅在异步函数中有效-node.js

时间:2019-04-23 17:13:49

标签: javascript node.js mongodb express async-await

我正在使用node并表示要为我的应用创建服务器。这是我的代码的样子:

async function _prepareDetails(activityId, dealId) {

  var offerInfo;
  var details = [];


  client.connect(function(err) {
    assert.equal(null, err);
    console.log("Connected correctly to server");

    const db = client.db(dbName);
    const offers_collection = db.collection('collection_name');

    await offers_collection.aggregate([
      { "$match": { 'id': Id} },
    ]).toArray(function(err, docs) {
      assert.equal(err, null);
      console.log("Found the following records");
      details = docs;
    });
  })
  return details;
}

app.post('/getDetails',(request,response)=>{

  var Id = request.body.Id;
  var activityId = request.body.activityId;
  _prepareDetails(activityId,Id).then(xx => console.log(xx));
  response.send('xx'); 
})

在调用getDetails API时我得到了

await is only valid in async function error (At line await offers_collection.aggregate)

在声明async function时,我的下划线也变成红色。我正在使用的节点版本是11.x。我也在使用firebase API。我在这里做什么错了?

1 个答案:

答案 0 :(得分:2)

您缺少其中一个函数的异步声明。这是工作代码:

async function _prepareDetails(activityId, dealId) {

  var offerInfo;
  var details = [];


  client.connect(async function(err) {
    assert.equal(null, err);
    console.log("Connected correctly to server");

    const db = client.db(dbName);
    const offers_collection = db.collection('collection_name');

    await offers_collection.aggregate([
      { "$match": { 'id': Id} },
    ]).toArray(function(err, docs) {
      assert.equal(err, null);
      console.log("Found the following records");
      details = docs;
    });
  })
  return details;
}

app.post('/getDetails', async (request,response)=>{

  var Id = request.body.Id;
  var activityId = request.body.activityId;
  let xx = await _prepareDetails(activityId,Id);
  response.send('xx'); 
})

等待只能在异步函数中使用,因为等待在定义上是异步的,因此必须使用回调或Promise范式。通过将函数声明为异步,您可以告诉JavaScript将响应包装在Promise中。您的问题在以下行中:

  client.connect(function(err) {

这是我如上所述添加异步的地方。

client.connect(async function(err) {

您会注意到,我也使您的路由也使用了异步,因为您之前曾经遇到过问题。请注意原始代码中的两行:

  _prepareDetails(activityId,Id).then(xx => console.log(xx));
  response.send('xx'); 

您的响应会在您进行数据库调用之前发送,因为您没有将response.send包装在.then中。您可以将response.send发送到.then,但是如果您要使用异步/等待,我会一直使用它。因此您的新路线将如下所示:

app.post('/getDetails', async (request,response)=>{

  var Id = request.body.Id;
  var activityId = request.body.activityId;
  let xx = await _prepareDetails(activityId,Id);
  response.send('xx'); 
})