Heim > Fragen und Antworten > Hauptteil
Endlich wird das Versprechen verwendet, das Problem zu lösen. Der Code lautet wie folgt:
exports.selectByUsername = selectByUsername;
function selectByUsername(username){
var promise = new Promise(function(resolve){
var sql = "SELECT COUNT(*) count FROM wx_user WHERE username = ?";
var sqlParams = [username];
var count;
co.query(sql,sqlParams,function(err,result){
if(err){
return console.log(err.message);
}
console.log("------------------------开始查询---------------------");
console.log(result);
var str = JSON.stringify(result);
var json = JSON.parse(str);
count = json[0].count;
console.log(count);
console.log("------------------------查询结束---------------------");
resolve(count);
});
});
promise.then(function(value){
// console.log(value);
return value;
});
return promise;
}
app.post('/ajax',urlencodedParser,function(req,res){
username = req.body.name;
console.log(username);
var promise = s.selectByUsername(username);
promise.then(function(value){
console.log(value);
if(value!==1){
res.send("用户名不存在");
}
});
});
Referenzdokument: http://liubin.org/promises-book/
天蓬老师2017-05-16 13:34:46
query里面的function在query完成后才会执行到,而这个时候外部函数已经返回了,所以count不会赋到值,仍然为undefined