1

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

1
  • 2
    You have one async function async function(req, res) but the await is not within it - you have await in the callback function(err, db) which is not async. Commented Dec 26, 2019 at 21:32

1 Answer 1

3

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);
  }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.