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