在promise链中混合变量

时间:2016-12-05 18:16:43

标签: javascript ecmascript-6 es6-promise

所以我有一个承诺链,解决了我遇到的某个回调地狱。

这是链条的样子:

server.exchange(oauth2orize.exchange.password(
    function(client, email, password, scope, done) {
        users.findOne({email: email})
            .then(authenticateUser) // mix in password here?
            .then(deleteExistingTokens) 
            .then(createAndSaveNewTokens) 
            .then(function(results){
                done(null, results[0], results[1], {'expires_in': tokenLife});
            }).catch(err => {done(err);});
    }));

所以 users.findOne 会返回一个返回我的用户的承诺。我需要混合在'用于进行身份验证的密码。鉴于这是我对authenticateUser的定义,我将如何在链中插入新变量?

const authenticateUser = (err, user) => { // add password here?
    return Promise((resolve, reject) => {
        if (!user) {
            reject('User not found');
        } 
        try {
            return User(user).authenticate(password)
            .then((result) => {
                if (result) {
                    resolve(user);
                } else {
                    reject('Invalid password');
                }
            });
        }
        catch (err) {
            reject('Invalid user');
        }
    });
};

1 个答案:

答案 0 :(得分:6)

您可以使用内联函数执行此操作:

.then(value => authenticateUser(value, password)) // mix in password here?

你必须更新authenticateUser,因为你问题中的签名是旧式的NodeJS回调,它不接受密码,而不是传递给{{1}的函数}。

也许这样的事情(见评论,但也继续阅读):

then

请注意,在上文中,我仅在const authenticateUser = (user, password) => { // We shouldn't need to create a new promise here, we have one // from `authenticate` below we can use return Promise((resolve, reject) => { if (!user) { // This shouldn't be reject('User not found'); // necessary...? } // ... try { // No `return` on th enext line, doesn't do anything // useful in the Ppromise init callback User(user).authenticate(password) .then((result) => { if (result) { resolve(user); } else { reject('Invalid password'); } }); } catch (err) { reject('Invalid user'); } }); }; 回调then回调中留下了逻辑,但它不应该使用{{1}解析对于用户,所以你的authenticate回调应该能够假设用户有效(这简化了上述内容)。如果身份验证失败,null拒绝

另请注意,由于then会返回承诺,因此我们不必在authenticate中创建新承诺。

以下是我对全新authenticate

的看法
authenticateUser
相关问题