Search code examples
javascriptexpressmongoosepromiseexpress-router

Promise not returning any data for fetch return


I´m building an express router that uses mongoose to access the database. My current problem relies on this piece of code:

app.use("/authreset", (req, res) => {
    authenticator
        .resetPassword(
            req.body.username,
            req.body.password,
            req.body.token,
            req.body.type
        )
        .then((response, error) => {
            if (error) throw new Error(error);

            console.log('*****************');
            console.log(response);

            if (!response) {
                res.sendStatus(401);
                return;
            }
        })
        .catch(error => {
            console.log('*****************');
            console.log(error);
            if (error) throw new Error(error);
        });

});

resetPassword uses the following mongoose call:

return UserModel
    .findByIdAndUpdate(user.id, data, { new: true })
    .exec();

For some reason, my route is being called and the response is fine (checked on console.log(response) inside promise).

My problem is that the response is never sent back to the client, that times out the fetch call.

Why is my promise not returning data?


Solution

  • Uh, you log the response, but you never send it (or at least respond with a status code)?

    Your code should look more like

    app.use("/authreset", (req, res) => {
        authenticator.resetPassword(
            req.body.username,
            req.body.password,
            req.body.token,
            req.body.type
        ).then(response => {
            console.log(response);
    
            if (!response) {
                return res.sendStatus(401);
            } else {
                return res.sendStatus(200); // <<<
            }
        }, error => {
            console.log(error);
            return res.sendStatus(500);
        });
    });
    

    Notice that the then callback never gets called with more than one argument, so that error you were checking for cannot happen. In the catch handler, you should never rethrow an error if it doesn't get handled further down. Also I changed .then(…).catch(…) to the more fitting .then(…, …).