Finally used promise to solve the problem, the code is as follows:
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("用户名不存在");
}
});
});
Reference document: http://liubin.org/promises-book/
天蓬老师2017-05-16 13:34:46
The function in the query will not be executed until the query is completed, and at this time the external function has returned, so count will not be assigned a value and is still undefined
给我你的怀抱2017-05-16 13:34:46
Writing it in query will not return count, because the query method is asynchronous