这个问题来自使用 Node.js 的 10gen MongoDB 类中的作业问题,但是,我并不是要您解决作业(关于 Mongo),而是要解释两个函数之间的关系。在 session.js 文件中,该方法在这样的数据对象模块addUser
上调用users
users.addUser(username, password, email, function(err, user) {
"use strict";
if (err) {
// this was a duplicate
if (err.code == '11000') {
errors['username_error'] = "Username already in use. Please choose another";
return res.render("signup", errors);
}
// this was a different error
else {
return next(err);
}
}
sessions.startSession(user['_id'], function(err, session_id) {
"use strict";
if (err) return next(err);
res.cookie('session', session_id);
return res.redirect('/welcome');
});
});
在用户数据对象模块中,有这样一个this.addUser
函数
this.addUser = function(username, password, email, callback) {
"use strict";
// Generate password hash
var salt = bcrypt.genSaltSync();
var password_hash = bcrypt.hashSync(password, salt);
// Create user document
var user = {'_id': username, 'password': password_hash};
// Add email if set
if (email != "") {
user['email'] = email;
}
//node convention first arg to call back error, 2nd the actual data we're returning, callbackwith value if added user
// look in session.js file that uses the UsersDAO to get a sense of how this is being used and
// what type of callback is passed in.Task is to fill in code to add a user when one tries to signup
// TODO: hw2.3
callback(Error("addUser Not Yet Implemented!"), null);
}
我们应该实现允许将用户添加到 mongo 数据库中的回调。我不是要你告诉我这些。相反, users.addUser 函数的第四个参数是一个回调函数function(err, user) { }
。另外,这个this.addUser
函数有callback
第四个参数,所以users.addUser
里面运行的回调函数this.addUser?
你能帮助澄清这两者之间的关系吗?我知道函数完成后会运行回调,但我不知道为什么将其传递给this.addUser