简体   繁体   中英

Await is only valid in async functions

I'm trying to rewrite my code to incorporate promises. I know that mongo already incorporates promises but i'd like to understand promises a bit more first. I don't understand the error message because I have used await in the async function . I found this articles that seems to do it similarly, but I still wasn't able to get it working.

What am i doing incorrectly here?

error message

SyntaxError: await is only valid in async function

code

 app.post('/search/word',urlencodedParser, async function(req, res){ try{ MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) { if (err) throw err; let dbo = db.db("words"); //Declare promise let searchWord = function(){ return new Promise(function(resolve, reject){ dbo.collection("word").find({"$text": {"$search": req.body.word}}) .toArray(function(err, result) { err ? reject(err) : resolve(result); }); }); }; result = await searchWord(); db.close(); res.setHeader('Content-Type', 'application/json'); res.send(JSON.stringify(result)); }); } catch(e) { console.log(e); } });

The callback functions needs to be async

app.post('/search/word',urlencodedParser, async function(req, res){
  try{
    MongoClient.connect(url, { useNewUrlParser: true }, async function(err, db) {
      if (err) throw err;
      let dbo = db.db("words");

      //Declare promise
      let searchWord = function(){
        return new Promise(function(resolve, reject){

          dbo.collection("word").find({"$text": {"$search": req.body.word}})
          .toArray(function(err, result) {
            err ? reject(err) : resolve(result);
          });
        });
      };

      result = await searchWord();

      db.close();
      res.setHeader('Content-Type', 'application/json');
      res.send(JSON.stringify(result));
    });

  } catch(e) {
      console.log(e);
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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