asynchronous error catcher wrapper function causing my returned promise to be undefined

I am building an api and am trying to create some cookies using req.cookie.

Originally i was encountering an in issue in that the cookies were not all being set before the response was sent out in my scynchronous code:

const createTokensAndCookies = catchAsync(async (req, res) => {
    const promises = [];
    promises.push(jwtToken.sign({ id: req.user._id }));
    promises.push(jwtRefreshToken.create());
    promises.push(csrfToken.create());
    const tokens = await Promise.all(promises);
    //create coookies
    jwtCookie.create(req, res, tokens[0]);
    jwtRefreshCookie.create(req, res, tokens[1]);
    csrfCookie.create(req, res, tokens[2]);

});

In an route handler i then called this function and in the next line called res.send().

To fix the issue i made createTokensAndCookies return a promise. So my code as it stands is:

const createTokensAndCookies = catchAsync(async (req, res) => {
    const promises = [];
    promises.push(jwtToken.sign({ id: req.user._id }));
    promises.push(jwtRefreshToken.create());
    promises.push(csrfToken.create());
    const tokens = await Promise.all(promises);
    //create coookies
    return new Promise((resolve, reject) => {
        jwtCookie.create(req, res, tokens[0]);
        jwtRefreshCookie.create(req, res, tokens[1]);
        csrfCookie.create(req, res, tokens[2]);
        resolve();
    });
});

The route handler:

exports.signUp = catchAsync(async (req, res, next) => {
    //get only certain variables out of req object
    const { body } = req;

    const user = await User.create({
        name: body.name,
        email: body.email,
        password: body.password,
        passwordConfirmation: body.passwordConfirmation,
    });
    req.user = user;
    createTokensAndCookies(req, res).then(() => {
        res.status(201).json({
            status: 'success',
        });
    });
});

And the catchAsync wrapper:

module.exports = (fn) => (req, res, next) => {
    fn(req, res, next).catch(next);
};

I am now getting the following error:
Cannot read property 'then' of undefined

Interestingly, when i remove the catchAsync wrapper everything works and the response isn’t sent until all cookies are created.

Does anyone know how i can do this whilst keeping the catchAsync warpper? An explanation of why removing the catchAsync wrapper solves the issue would also be great.

11 thoughts on “asynchronous error catcher wrapper function causing my returned promise to be undefined”

Leave a Comment