koa-router路由函数中调用函数后,怎样将通过回调函数中得到的值返回给前端
路由函数如下:
route.post('/readport',function *(){
var postdata = yield parse(this);
var dataproject = postdata["selectedpro"];
var portname =[] ;
yield portname;
mysqlinsertp.selectport(dataproject,function(comerr,row){
if(row.length == 0){
console.log("没有信息");
}
else{
for(var i = 0; i < row.length; i++){
portname[i] = row[i].portname;
}
//var result = '{ "status": "200", "ok": "true", "data": "'+portname+'" }';
//this.body = JSON.parse(result); //尝试在这里返回,但前台获取不到值
}
});
yield portname;
var result = '{ "status": "200", "ok": "true", "data": "'+portname+'" }';
this.body = result;//在这里返回的话因为这里比上面函数先执行,所以portname的值为空
});
请教怎么样可以把得到值的result赋值给this.body后返回给前端ajax请求
操作数据库函数声明如下:
exports.selectport = function(projectname,callback){
client.query('SELECT DISTINCT portname FROM invoketable where projectname =?',projectname, function(err, results) {
var count = Object.keys(results).length;
if(count == 0) {
return ;
}
else{
console.log(results);
callback(null, results);
}
});
}