Home > Mobile >  Javascript - Error: Route.post() requires a callback function but got a [object Promise]
Javascript - Error: Route.post() requires a callback function but got a [object Promise]

Time:09-21

One of my express routes is giving me the following error:

Error: Route.post() requires a callback function but got a [object Promise]

It's because of the last line in controllerFunction:

// IN CONTROLLER.JS
exports.controllerFunction = async (req, res) => {
    //Get some values
    let foos = await User.somefunction();
    
    for(foo in foos){
        //Call some async void functions
    }
    res.status(200).send('DONE')
}

...

// IN ROUTER.JS
router.post('/', validation, validate, checkLoggedIn, checkUserPermission(1), async(req, res, next) => {
    try{
        await controller.controllerFunction(req, res)
    } catch (error) {
        next(error);
    }
});

I figured I need to return a callback function, but I'm not sure how. The rest of my controller functions look like that and they work because of the .then():

// IN CONTROLLER.JS
exports.getCameras = async (req, res) => {
    await Model.getCameras(req.machine)
        .then(cameras => res.send(cameras));
}

But in my controllerFunction I can't call .then() due to the fact that I need to do some logic beforehand in a for loop, so I need to generate the callback function in some other way.

How could I make controllerFunction a callback function?

CodePudding user response:

try this.

return res.status(200).send('DONE');

exports.controllerFunction = async (req, res) => {
    //Get some values
    let foos = await User.somefunction();
    
    for(foo in foos){
        //Call some async void functions
    }

    return res.status(200).send('DONE');
}

CodePudding user response:

As @slebetman stated in the comments, one of the functions called in the router was incorrect:

router.post('/', validation, validate, checkLoggedIn, checkUserPermission(1), async(req, res, next) => {}

Make sure validation, validate and checkLoggedIn are all functions and not a return value

checkUserPermission(1) was incorrect since that function wasn't expecting any parameters to be passed, changed to checkUserPermission and it worked.

  • Related