我在Node.js中編寫了一個基本的用戶創建系統,我想了解createUser函數的結果。代碼本身工作正常,發佈新用戶,現有用戶被停止。我想向最終用戶展示這一點,所以我設置了一個變量來返回表示結果的數值。Javascript未分配給變量
問題是,該值永遠不會分配給。即使我的其他日誌語句出現,最終的控制檯日誌也總是讀取未定義的。我覺得這更像是一個JavaScript語法問題,但我很難過。
User.prototype.createUser = function() {
console.log('Begin createUser...');
var email = this.email;
var wasUserCreated; <------- variable to assign
pg.connect(process.env.DATABASE_URL, function (err, client) {
if (err) {
console.log(err.message, err.stack);
wasUserCreated = 0; <------assigning to variable?
}
else {
var query = client.query('SELECT email FROM users WHERE email=$1', [email],
function (err, results) {
if (results.rows.length > 0) {
console.log('That email address has already been registered!');
wasUserCreated = 1; <------assigning to variable?
}
else {
console.log('Email address not found, inserting new account');
insertNewUser();
wasUserCreated = 2; <------assigning to variable?
}
});
}
});
console.log("wasUserCreated: " + wasUserCreated); <------always reads 'undefined'
return wasUserCreated;
};
** A **同步。不相關的,但我會迴避使用數值來實現本質上的布爾值。 –