【问题标题】:ExpressJS chain promises call multiple times the next() functionExpressJS 链承诺多次调用 next() 函数
【发布时间】:2017-03-31 05:46:55
【问题描述】:

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

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

我可以不将这两个 Promise 链接起来,而只是在另一个 Promise 中使用一个 Promise,但如果有人有一个很好的模式来解决这种错误处理,可能我的代码是错误的,或者我错过了关于 Promise 的一些内容。

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

注意:我使用的是个人方法 res.setError() 或 res.setResponse() 这只是帮助我管理请求状态,然后我使用 res.send 下一个中间件函数

谢谢大家

【问题讨论】:

    标签: javascript node.js express middleware es6-promise


    【解决方案1】:

    当您在.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
    });
    

    【讨论】:

    • 感谢您的回复,这就是我的想法。 - 这是在承诺中以这种方式抛出错误的好模式吗?我是 Promise 的新手,我只是使用了 nodeJS function(err, res)` 模式,因为回调不允许使用 try / catch,因此使用 throw Error
    猜你喜欢
    • 2017-08-12
    • 2018-07-06
    • 2017-03-26
    • 2016-10-19
    • 1970-01-01
    • 2018-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多