koa2,异步mysql查询,返回数据渲染页面
过程是这样,当用户输入账号密码后,根据查表的结果渲染不同的页面,可是mysql查询是异步的,导致无论查询结果是什么,渲染的页面都是 ‘not found’
var fn_login = async(ctx, next)=>{
var name = ctx.request.body.name || '',
password = ctx.request.body.password || '';
connection.connect();
connection.query(`select * from member where user='${name}' and password='${password}'`, function(error, results){
if(error) throw error;
if(results.length){
ctx.response.body = template({
login: true,
name: name
})
} else {
ctx.response.body = template({
login: false
})
}
});
};
module.exports = {
'POST /login': fn_login
}
2 回复
这代码callback跟同步混搭 要promise包装下callback
let docs = await new Promise((resolve,reject)=>{
connection.query(`select * from member where user='${name}' and password='${password}'`, function(error, results){
if(error) throw error;
if(results.length){
resolve({
login: true,
name: name
})
} else {
ctx.response.body = template({
login: false
})
}
});
})
ctx.response.body = template(docs)
@chong0808 懂了,多谢