Simon Bruneaud Simon Bruneaud - 21 days ago 6
Javascript Question

ExpressJS chain promises call multiple times the next() function

I'm using a middleware that handle logic for creating new users in the db. This function just check if the user email already exist, if not it's creating new doc, otherwise it just send an error to the client.

The issue in this function (below) is that the next() middleware function is called twice when user email already exist in the db

I could just do not chain these two promises and just use a promise inside another, but if someone has a good pattern to resolve this kind of errors handling, maybe my code is wrong, or I missed something about promises.

create: function(req, res, next) {

// Check if email already exist
userDB.byEmail(req.body.email).then(function(doc) {

if (doc) {
res.setError('This email already exists', 409);
return next();
}

// Return other Promise
return userDB.create(req.body);

}).then(function(doc) {

res.setResponse(doc, 200);
return next();

}).catch(function(err) {

res.setError('Service seems to be unavailables', 503);
return next();
});
},



Note: I'm using personal methods res.setError() or res.setResponse()
that just help me to manage request state, then I use res.send with
the next middleware function


Thanks guys <3

Answer

When you do return next() in the .byEmail callback you are continuing the promise chain, so the next .then that does res.setResponse(doc, 200) also ends up getting called. You either need to break the promise chain by throwing or set the response in one spot.

if (doc) {
   const error = new Error('This email already exists');
   error.status = 409;

   throw error;
}
// ...
.catch(err => {
   res.setError(err.message, err.status);
   return next(); // you may not even want to do this in the case of errors
});