0

I am using node.js express framework to create REST API and trying to convert my code from callbacks to Async/Await methods with basic .then() promise using artical . so while implementing code getting error as SyntaxError: await is only valid in async function

I am new to javascript and not understand what is cause this issue. I have below folder structure

 MAIN APP
    ├── app.js
    ├── controllers
    │   └── UserController.js
    ├── routes
    │   └── User.js
    └── util
        ├── AuthUtil.js
        ├── Helpers.js
        ├── RestUtil.js
        └── wallet.js
 

My backend API controller function is below

Getone: async (req, res, next) => {
    try {
    MongoClient.connect(config.Database.DFARM.connectString, function(err, client) {
       assert.equal(null, err);
       const db = client.db(config.Database.DFARM.dbName);
      console.log('********db**********',db)
       //Step 1: declare promise

        var myPromise = () => {
           return new Promise((resolve, reject) => {

              db
              .collection('User')
              .find(query)
              .limit(1)
              .toArray(function(err, docs) {
                 err
                    ? reject(err)
                    : resolve(docs[0]);
               });
           });
        };
       //await myPromise
       var result = await myPromise();
       //continue execution
       client.close();
       console.log('********result**********',result)

    //    res.json(result);
    }); //end mongo client
    } catch (e) {
       next(e)
    }
    }

My router

router.get('/getone/:id', function (req, res, next) {
    controller.Getone(req, res, next);
});

2 Answers 2

2

So, basically the nested function is not async. so you need to:

async function(err, client) {/* your code */}

BTW, why are you constructing new promise inside the async function? you can just do the next:

Getone: async (req, res, next) => {
  try {
   const client = await MongoClient.connect(config.Database.DFARM.connectString)
   const db = client.db(config.Database.DFARM.dbName);
   const result = await db
          .collection('User')
          .find(query)
          .limit(1)
          .toArray(function(err, docs) {
             err
                ? reject(err)
                : resolve(docs[0]);
           });
       });
   // do something with result..
   client.close();
   console.log('********result**********',result)
  } catch (error) {
    // handle error
  } 
};
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks@Yakir for suggestion and help
1

The function "function (err, client)" are not async and you are using await inside. So you get this error. Try "async function (err, client)"

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.