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邮件是否有效。
- 将非结构化数据保存在mongoose中
- 来自node.js的MongoDB查询(express-coffeescript-mongodb)
- 转发表示js路由到其他服务器
- GraphQL-js Node / Express:如何在GraphQL Query中传递一个弦乐对象?
- Backbone.js pushState路由与node.jsexpression服务器帐户?
- 如何解码一个节点应用程序中的谷歌OAuth 2.0 JWT(OpenID连接)?
- 当modelObject从数据库本身获得时,modelObject.save()是否只更新现有的数据库文档?
- 在Node.js中处理回滚的MySQL事务
- 是否使用快速会话回收过期的会话ID