Personal Information
Personal Information

Reputation: 581

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

Upvotes: 1

Views: 121

Answers (1)

Thales
Thales

Reputation: 346

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

Upvotes: 3

Related Questions