app.js中的路由调用MySQL模型model.js中的函数寄存器(用户)。这个register()调用displayNameTaken(display_name),如果显示名称可用,它将返回null,否则它将返回一个json对象。
包含model.register(req.body)的app.post中的promise无法解析。
如果显示名称,register()会将此json对象传递回调用路径。
如果未获取显示名称,则register()将注册用户并将另一个json对象返回给主叫路由。
该应用程序永远无法解析返回的承诺,即应用程序#113。 或者您对我应该做什么有任何建议吗? 你能看出我做错了什么吗?
以下输出:
1. When display name taken
app#113 [ undefined ]
model#73 { code: 12, message: 'e' }
2. Display name not taken, registration successful
app#113 [ undefined ]
model#73 undefined
model#61 110 //<- last insert id
The app never resolves the returned promise, app#113.
Or do you have any suggestions to what I should do instead?
Can you see what I have done wrong?
app.post('/api/register', function (req, res) {
Promise.all([
model.register(req.body)
]).then((r => {
console.log('app#113',r);// r=> undefined
res.status(200).json(r);
})).catch((e => {console.log(e);
res.status(500).json(e);
}));
});
function Model(db){
this.db = db;
}
//Function returns null if display name is not taken
Model.prototype.displayNameTaken = function(display_name){
return new Promise((resolve, reject, next) => {
var sql = "SELECT id FROM `users` WHERE `display_name` = ?";
var rv;
this.db.query(sql, [[display_name]], (err, result) => {
if (err) {
return resolve(err);
}
if(0 < result.length && result[0].id != undefined && result[0].id != NaN && 0 < result[0].id){
rv = {code: 12, message:'e'};
}else{
rv = null;
}
return resolve(rv);
});
});//Promise
}
model.register = function register(params){
if(params == undefined){
return;
}
var rv;
Promise.all([
this.displayNameTaken(params.display_name.trim())
]).then((r => {
return new Promise((resolve, reject, next) => {
if(r[0] == null){//display_name available
var sql = "INSERT INTO `users` (`display_name`, `email`, `hash`, `created`,`md51`, `md52`, `language`) VALUES ?";
var md51 = md5(randomString({length:32}));
var md52 = md5(randomString({length:32}));
var user = [[
params.display_name.trim(),
params.email.trim(),
passwordHash.generate(params.hash.trim()),
datetime.create().format('Y-m-d H:M:S'),
md51,
md52,
params.language
]];
this.db.query(sql, [user], function (err, result) {
if (err) {
return reject(err);
}
console.log('model#61',result.insertId);
if(0 < result.insertId){
rv = {code: 8, message:'i', md51: md51, md52: md52};
}else{
rv = {code: 0, message:'e'};
}
return resolve(rv);
});
}else{//display_name taken
rv = r[0];
}
console.log('model#73',rv);
return resolve(rv);
});//Promise
})).catch((e => {
console.log(e);
}));