ExpressJS 链承诺多次调用 next() 函数

ExpressJS chain promises call multiple times the next() function

我正在使用一个中间件来处理在数据库中创建新用户的逻辑。此函数仅检查用户电子邮件是否已存在,如果不存在则创建新文档,否则仅向客户端发送错误。

此函数(如下)中的问题是,当用户电子邮件已存在于数据库中时,next() 中间件函数被调用两次

我可以不链接这两个 promise,而是在另一个 promise 中使用一个 promise,但是如果有人有一个很好的模式来解决这种错误处理,也许我的代码是错误的,或者我错过了一些关于 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

谢谢大家 <3

当您在 .byEmail 回调中执行 return next() 时,您正在继续承诺链,因此执行 res.setResponse(doc, 200) 的下一个 .then 最终也会被调用。您要么需要通过 throwing 打破承诺链,要么在一个地方设置响应。

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
});