Tobol
Tobol

Reputation: 107

Express pass parameter to async middleware

I have a synchronous middleware to authorize role. It's set up like this:

Route:

router.get("/test", [authorizeRole("tier1", "tier2")], function(req, res) {})

Middleware:

module.exports = function authorizeRoles(...role) {
    return (request, response, next) => {
        //authorize
    };
};

This is working. Now i want to change my middleware to make it async.

I can't figure out how to make the middleware async. I tried:

module.exports = async function authorizeRoles(...role) {
    return await (request, response, next) => {
        //authorize
    };
};

module.exports = async function authorizeRoles(...role) {
    return await async (request, response, next) => {
        //authorize
    };
};

But nothing works.

How can i make the middleware async?

Upvotes: 3

Views: 2092

Answers (1)

ThomasThiebaud
ThomasThiebaud

Reputation: 11969

I'm not sure I completely understood your question. To use await you need to declare your function using the async keyword, so this should work

module.exports = function authorizeRoles(...role) {
    return async (request, response, next) => {
        // now you can use `await` here
    };
};

Upvotes: 4

Related Questions