【问题标题】:Is wrapping an ES6 promise within another an anti-pattern?将 ES6 承诺包装在另一个反模式中吗?
【发布时间】:2019-12-29 12:07:48
【问题描述】:

我查看了Brad Traversy's User routes for DevConnector,这是他用来教授 Node.js 的一个项目。在我看来,代码看起来不够简洁或不言自明;例如,看看/register 路线 - 它都写在一个大块中。我想知道在其他承诺中包装承诺是否可以解决这个问题。

下面是我的替代方案:

router.post('/register', (req, res) => {
    const firstName = req.body.firstName;
    const lastName = req.body.lastName;
    const email = req.body.email;
    const password = req.body.password;
    const dateOfBirth = req.body.dateOfBirth;

    buildUserIfNotExists(email, firstName, lastName, dateOfBirth)
        .then(user => hashUserPassword(user, password, 10))
        .then(user => saveUser(user))
        .then(user => {
            sendActivationLink(user);
            res.json(user);
        })
        .catch(errors => {
            if (errors.internalError) {
                console.log(errors.internalError);

                res.status(500).json({
                    internalError: 'An internal error occured.'
                })
            } else {
                res.status(400).json(errors);
            }
        });
});

我看到的 Promise 包装器的一个例子是:

function saveUser(user) {
    const errors = {};

    return new Promise((resolve, reject) => {
        user
            .save()
            .then(user => resolve(user))
            .catch(err => {
                errors.internalError = err;

                reject(errors);
            })
    });
}

到目前为止,我对这种方法没有任何问题,一切都按预期工作。我想念这个有什么缺点吗?有什么办法可以进一步简化?

【问题讨论】:

标签: javascript asynchronous concurrency promise es6-promise


【解决方案1】:

我对 JavaScript 不是很有经验,但我发现了以下简化;而不是:

.then(user => saveUser(user))

我可以这样做:

.then(user => user.save())

其实经过一些修改,我的代码是这样的:

router.post('/register', (req, res) => {
    const newUser = new User({
        name: req.body.name,
        hometown: req.body.hometown,
        dateOfBirth: req.body.dateOfBirth,
        email: req.body.email,
        activationHash: nanoid()
    });

    ensureUserNotExists(newUser)
        .then(() => hashUserPassword(newUser, req.body.password))
        .then(() => newUser.save())
        .then(() => {
            sendActivationLink(newUser).then(() => res.json(newUser))
        })
        .catch(errors => {
            if (errors.internalError) {
                console.log(errors.internalError);

                res.status(500).json({
                    internalError: 'An internal error occured.'
                })
            } else {
                res.status(400).json(errors);
            }
        });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    • 2016-02-23
    • 2018-04-23
    相关资源
    最近更新 更多