简体   繁体   English

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

[英]await is only valid in async function - nodejs

I'm using node and express to create server for my app. 我正在使用node和express为我的应用创建服务器。 This is how my code looks like: 这是我的代码的样子:

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'); 
})

While calling getDetails API I am getting 在调用getDetails API时

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

I am also getting red underline while declaring async function . 在声明async function时,我也得到了红色下划线。 Node version I'm using is 11.x. 我正在使用的节点版本是11.x。 I'm also using firebase API. 我也在使用firebase API。 What am I doing wrong here? 我在这里做错了什么?

You are missing the async declaration on one of your functions. 您缺少其中一个函数的异步声明。 Here is the working code: 这是工作代码:

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'); 
})

Await can only be used in an async function, because await is by definition asynchronous, and therefore must either use the callback or promise paradigm. 等待只能在异步函数中使用,因为等待在定义上是异步的,因此必须使用回调或promise范式。 By declaring a function as async, you are telling JavaScript to wrap your response in a promise. 通过将函数声明为异步,您可以告诉JavaScript将响应包装在Promise中。 Your issue was on the following line: 您的问题在以下行中:

  client.connect(function(err) {

This is where I added the async as mentioned before. 这是我如上所述添加异步的地方。

client.connect(async function(err) {

You will notice I made your route use async also, because you would've had an issue before. 您会发现我也使您的路由也使用了异步,因为您之前曾遇到过问题。 Notice the two lines in your original code: 请注意原始代码中的两行:

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

Your response would send before you even made your database call because you are not wrapping the response.send within the .then. 您的响应会在您进行数据库调用之前发送,因为您没有将response.send包装在.then中。 You could move the response.send into the .then, but if you are going to use async/await, I would use it all the way. 您可以将response.send发送到.then,但是如果您要使用异步/等待,我会一直使用它。 So your new route would look like: 因此,您的新路线将如下所示:

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'); 
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM