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

我正在使用护照本地策略进行用户注册。 我碰到这个代码示例,其中作者正在使用process.nextTick来延迟Passport LocalStrategycallback中的方法的执行。 我知道我们可以使用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); })); 

这是因为作者想保持函数总是asynchronous的。 在代码片段中,如果isValidEmail(user)返回false,则此代码是同步的(因为它不包含任何io操作)。 通过延迟执行,error handling程序将被调用,以便该句柄始终是asynchronous的,而不pipe邮件是否有效。