读取数据库内容函数,所在文件mysqloperate.js
exports.selectpro = function*(cb){ var sql = “SELECT DISTINCT projectname FROM invoketable”; var projectname; client.query(sql,function(err, rows, fields) { if(err) { cb(err, null); } else { projectname = rows[0].projectname; console.log(‘select projectname from db’); console.log(rows[0].projectname); cb(null, rows[0].projectname); } }); };
路由中调用上面函数,取出得到的数据返回给页面
route.get(’/readproject’,function *(){ var dataprodect; var a; yield mysqlinsertp.selectpro(function(err, res){ if (err) throw err; dataprodect = res; console.log(res); }); console.log(“dataprodect”); console.log(dataprodect); this.body={status:200,ok:true,data:dataprodect}; console.log(this.body); });
前端调用请求
$.ajax({ url: “/readproject”, type: “GET”, dataType: ‘json’, data: null, success:function(res){ if(res.status == 200){ if(res.data == null){ console.log(“no data”); } else{ var last = JSON.stringify(res); console.log(last); } } }, error:function(err){ console.log(err); } });
得到输出: dataprodect //并没有按顺序输出 undefined { status: 200, ok: true, data: undefined } //因为异步dataprodect并没有得到返回的值,求这里得到值得做法 select projectname from db projectname1 projectname1
求指导
@lonso exports.selectpro = function(cb)这个函数改为generator之后 yield好像并没有起作用 返回为 { status: 200, ok: true, data: undefined } select projectname from db projectname1 projectname1
@Gdreamlend 你把 “SELECT DISTINCT projectname FROM invoketable” 改为 “SELECT * projectname FROM invoketable”试一试