Himmators Himmators - 5 months ago 9
Node.js Question

Pass values from referenced function in promise-chain?

I'm writing some rendering-code for an Express app, I wish to catch errors and then output them in the function render, but I'm not sure how I'm going to move them from one method to the other.

app.get('/user/makeRider', auth,
(req, res, next) => {
req.user.user.makeRider(req.query)
.catch(error)
.then(render(req, res));
}
);

var render = (req, res) => {
var response = {
params: req.query,
user: req.user.fulluser
};
res.json(response);
},
error = (reason) => {
reason.errors.forEach((error) =>{
console.log(error);
});
return;
};

Answer

You can use error function as your last midleware in the chain and simply pass the request to the next chain:

var render = (req, res) => {
    var response = {
        params: req.query,
        user: req.user.fulluser
    };
    res.json(response);
}

app.get('/user/makeRider', auth,
    (req, res, next) => {
        req.user.user.makeRider(req.query)
            .catch(next)
            .then(render(req, res));
    }
);

app.use((reason, req, res, next) => {
    res.send(reason.errors);
    // or you can send them as json: res.status(404).json({errors: reason.errors})
});

Beware of hoisting issue in your code, the variable declarations are hoisted to the top, but not their assignments, error and render function may appear as undefined when accessed from your route.

Comments