小白问题,异步惹的祸
发布于 17天前 作者 SevenSharp 293 次浏览 来自 问答

这是 index.js 代码:**** var db_sql = require(‘./mysql_db’); console.log(db_sql.Select_byName(‘Tom’)); 这是 mysql_db.js代码:

var mysql = require('mysql');

var conn =mysql.createConnection({
    host:'localhost',
    user: 'root',
    password:null,
    database:'nodejs',
    port:3306
});

var sql;

exports.Delete_ByName = function(name){
        sql ="delete from User where UserName = '"+name+"'";
        Query();
}
exports.Update_ByName = function(name,val){
        sql = "update User set UserName ='"+val+"' where Username='"+name+"' ";
        Query();
}
 exports.Select_byName = function(name){
        sql = "select * from User where UserName ='"+name+"'";
        return  Query();
}
exports.Insert_Date = function(val){
        sql = "insert into User values("+val+")";
        Query();
}
function Query(){

conn.connect();
conn.query(sql,function(err,results){
    if (err) {
    throw err;
};
    
});
conn.end(function(err){
    if (err) {
        throw err;
    };
    console.log('mysql close');
});

} 问题来了,Select_byName这个返回值results怎么得到?

10 回复

给代码上下都加上``` ,下次管理员是不会再帮你改了的@i5ting

@SevenSharp 恩对,貌似漏掉了个花括号,markdown语法参考这里 http://www.ituring.com.cn/article/775

@luoyjx 明白了。。代码缩进就可以了

一般不带这样层层嵌套的,如果你一定要这样写的话,就加个callback,

exports.Select_byName = function(name, callback){
       sql = "select * from User where UserName ='"+name+"'";
       return  Query(callback);
}
function Query(callback){//加callcack

conn.connect();
conn.query(sql,callback);
conn.end(function(err){
   if (err) {
       throw err;
   };
   console.log('mysql close');
});

调用的时候就db_sql.Select_byName(‘Tom’, function(err, results){ console.log(results)})

exports.Query= function(sql,callback){
....
....
callback(err,results)
}

@njaulj 那一般逻辑不是分开的吗。。这个写回到函数比较麻烦一些

@njaulj 一般逻辑是怎么写的不分层吗?

@SevenSharp node 的逻辑可以这样写

Db.conn(str)
    .query(sql)
    .exec(callback)


回到顶部