我的以下代码有两个问题。它是用于注册存储在mysql数据库中的用户的node.js模块的开始。
第一个问题是在第一个查询的回调中,变量this.connection是未定义的。第二个问题是,变量user在同一回调中也是未定义的。因此,代码在以下行崩溃:
this.connection.query('INSERT INTO users{{values values}}', {
values: {
user_name: user.username,
user_email: user.email,
user_password: user.password
}
})
请让我知道如何以适当的方式解决此问题。
非常感谢!
完整代码如下:
module.exports = usermodel;
//connection is a mysql-wrapper connection
function usermodel(connection)
{
this.connection = connection;
}
playermodel.prototype = {
registerByEmail: function (user, callback) {
//check firts if the user already exists
this.connection.query('SELECT user_id FROM users {{where data}}', {
data: {
user_email: user.email
}
},
function (err, result) {
if (err) {
...
} else if (result.length > 0) {
...
} else {
// this.connection is undefined ????????????
this.connection.query('INSERT INTO users {{values values}}', {
values: {
user_name: user.username,
user_email: user.email,
user_password: user.password
}
}),
function (err, result) {
...
}
}
});
}
}
this.connection
未定义,因为this.connection位于playermodel
传递给第一个查询的回调函数的实例上,它不知道playermodel实例的上下文。
user
应该定义。您可以this.connection
通过绑定函数或this
在回调将有权访问的变量中设置对的引用来解决未定义问题。
//Bind
playermodel.prototype = {
registerByEmail: function (user, callback) {
//check firts if the user already exists
this.connection.query('SELECT user_id FROM users {{where data}}', {
data: {
user_email: user.email
}
},
function (err, result) {
if (err) {
...
} else if (result.length > 0) {
...
} else {
// this.connection is undefined ????????????
this.connection.query('INSERT INTO users {{values values}}', {
values: {
user_name: user.username,
user_email: user.email,
user_password: user.password
}
}),
function (err, result) {
...
}
}
//HERE
}.bind(this));
}
}
or
//me reference to this
playermodel.prototype = {
registerByEmail: function (user, callback) {
//HERE
var me = this;
//check firts if the user already exists
this.connection.query('SELECT user_id FROM users {{where data}}', {
data: {
user_email: user.email
}
},
function (err, result) {
if (err) {
...
} else if (result.length > 0) {
...
} else {
//HERE
me.connection.query('INSERT INTO users {{values values}}', {
values: {
user_name: user.username,
user_email: user.email,
user_password: user.password
}
}),
function (err, result) {
...
}
}
});
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句