Boy
Boy

Reputation: 612

Right way to call async function inside express js route

This is how I am doing now. but trying to see if there is a right or another way to do it.

async function getmanual_vars(req, res,ajax){
    var return_data = {};
    let db = await mongo_client.connect(mongo_url);

    let db_data = await db.collection('data').find({ created_by_user_id: req.cookies.user_id}).toArray();

    // more codes inside //

    res.json({ success: true});
}

router.post('/manual_vars', check_auth,function(req, res, next) {
    getmanual_vars(req, res,0);
});

Upvotes: 4

Views: 2455

Answers (1)

Yee Hui Poh
Yee Hui Poh

Reputation: 366

You can do it this way:

async function getmanual_vars(req, res) {
  try {
    var return_data = {};
    let db = await mongo_client.connect(mongo_url);

    let db_data = await db.collection('data').find({
      created_by_user_id: req.cookies.user_id
    }).toArray();

    // more codes inside //

    res.json({ success: true});
  } catch (error) {
    res.status(500).json({ success: false, error: error });
  }
}

router.post('/manual_vars', check_auth, getmanual_vars);

This should have a catch for the possible errors and exceptions from your async function with status 500.

As this is already a function that takes in req and res, we can just pass in the function itself to the router instead of having to create a wrapper around it.

Upvotes: 1

Related Questions