user10021033
user10021033

Reputation:

How to add "async" to a route with a custom middleware?

I need to use await inside a route on Express, therefore it must be async. However, when I try to add async to the route, it does not work because I use a middleware.

api.get('/users/yop', CORS(CORSOPT), async, checkauth, (req, res) => {
  await GETDATA.getUsers(db.collection('users'));
  res.json(users[req.user]);
})

Middleware looks like this:

function checkauth(req, res, next) {
 ...
 next();
}

If async and checkout are separed by commas like in the code I posted, I get this error: await is only valid in async function

If they are not separated by commas, my code editor marks it as syntax error: enter image description here

How to fix this?

Upvotes: 0

Views: 58

Answers (4)

Fabio Lopez
Fabio Lopez

Reputation: 527

You can add async to the callback function:

api.get('/users/yop', CORS(CORSOPT), checkauth, async (req, res) => {
  await GETDATA.getUsers(db.collection('users'));
  res.json(users[req.user]);
})

Also if you want checkauth to return a promise for any reason, this is where you put the async:

async function checkauth(req, res, next) {
 ...
 next();
}

Upvotes: 0

byte-this
byte-this

Reputation: 214

Put the "async" directly in-front of the function you are passing in, not the references to the other functions. If those needed async, they can have their own declarations when those functions are defined themselves.

api.get('/users/yop', CORS(CORSOPT), checkauth, async (req, res) => {
  await GETDATA.getUsers(db.collection('users'));
  res.json(users[req.user]);
})

Upvotes: 0

Ian H.
Ian H.

Reputation: 3919

You need to declare the arrow function as async directly using the keyword.

api.get('/users/yop', CORS(CORSOPT), checkauth, async (req, res) => {
    await GETDATA.getUsers(db.collection('users'));
    res.json(users[req.user]);
});

Upvotes: 0

Siddharth
Siddharth

Reputation: 469

The syntax you're trying is not valid. async always goes with the function definition.

api.get('/users/yop', CORS(CORSOPT), checkauth, async (req, res) => {
  await GETDATA.getUsers(db.collection('users'));
  res.json(users[req.user]);
})

should work. If checkauth too contains await statements, mark the definition of checkauth as async.

Upvotes: 3

Related Questions