Express + PassportJs:为什么我们需要在护照策略中使用process.nextTick()延迟执行方法?

时间:2016-04-10 07:42:41

标签: javascript node.js express passport.js

我正在使用护照本地策略进行用户注册。我遇到了这个代码示例,其中作者正在使用process.nextTick来延迟在Passport LocalStrategy回调中执行方法。我知道我们可以使用process.nextTick延迟某些方法的执行,并在事件循环的下一个时间点执行它,但是你能解释一下为什么我们需要在这个例子中使用它吗?

passport.use('signup', new LocalStrategy({
    usernameField: 'email',
    passReqToCallback: true // allows us to pass back the entire request to the callback
},
function(req, email, password, done) {

    findOrCreateUser = function() {
        if (isValidEmail(email)) {
            // find a user in Mongo with provided email
            User.findOne({
                'email': email
            }, function(err, user) {
                // In case of any error, return using the done method
                if (err) {
                    console.log('Error in SignUp: ' + err);
                    return done(err);
                }
                // already exists
                if (user) {
                    console.log('User already exists with email: ' + email);
                    return done(null, false, req.flash('message', 'User Already Exists'));
                } else {
                    // if there is no user with that email
                    // create the user
                    var newUser = new User();

                    // set the user's local credentials
                    newUser.email = email;
                    newUser.password = createHash(password);

                    // save the user
                    newUser.save(function(err) {
                        if (err) {
                            console.log('Error in Saving user: ' + err);
                            throw err;
                        }
                        console.log('User Registration succesful');
                        return done(null, newUser);
                    });
                }
            });
        } else {
            console.log('Not a valid Email!');
            return done(null, false, req.flash('message', 'Invalid Email!'));
        }
    }

    // Delay the execution of findOrCreateUser and execute the method
    // in the next tick of the event loop
    process.nextTick(findOrCreateUser);
}));

1 个答案:

答案 0 :(得分:1)

这是因为作者希望保持函数始终是异步的。在代码段中,如果isValidEmail(user)返回false,则此代码是同步的(因为它不包含任何io操作)。通过延迟执行,下一个tick会调用错误处理程序,这样无论电子邮件是否有效,此句柄始终是异步的。