登录

node.js - node中MYSQL的异步问题

我在用node查询数据库中使用如下代码:
var _password =mysql.query(table," where name = " + "'" + name + "'","password");
其中mysql.query为
query(table,others,column){

    var connection = this.connection;
    var sql;
    if(column) sql = "select " + column + " from " + table;
    else{sql = "select * from " + table;}
    if(others) sql += " " + others;
    console.log(sql);
    var result;
    connection.query(sql,function(err,rows,fields){
        if(err){
            throw err;
        }
        if(rows.length > 1){
            rows.forEach(function(row){
                console.log(row);
            });
        }
        else if(rows.length == 1){
            console.log(rows[0]);
            rows = rows[0];
        } 
        else{
            console.log("没有数据");
        }
        return rows;
    });
    console.log('result:');
    console.log(result);
    return result;
}

最终的结果是:

很显然query之后的语句先执行了,此处无法使用yield,请大神指教

# MySQL
迷茫 迷茫 2273 天前 494 次浏览

全部回复(1) 我要回复

  • 天蓬老师

    天蓬老师2017-04-17 16:34:45

    rows.forEach(function(row){
       console.log(row);
    });

    这里面的循环是异步的,所以出问题了,你要控制住异步。

    给你一个例子,我刚学着写,应该写的不咋地,但是可以给你演示如何控制异步。

    这里是引用的cc这个model里的,不写全了,大概看一下
      getGrades: async () => {
        return new Promise((resolve, reject) => {
          db.pool.query('SELECT * FROM set_grades', function (err, rows) {
            if(rows){
              resolve(rows);
            }
            else{
              console.log(err);
              reject(err);
            }
          });
        });
      },
    
      getTerms: async (grade_id) => {
        return new Promise((resolve, reject) => {
          db.pool.query('SELECT * FROM set_terms WHERE grade_id = ?', grade_id,function (err, rows) {
            if(rows){
              resolve(rows);
            }
            else{
              console.log(err);
              reject(err);
            }
          });
        });
      },
    
    
    // ------------创建合同-------------
    exports.createContract = async (ctx, next)=> {
      // 1 获取types
      let types = new Array();
      await cc.getTypes().then(result => {
        types = result;
      });
    
      // 2 获取cats
      let cats = new Array();
      await cc.getCats().then(result => {
        cats = result;
      });
    
      // 3 获取grades
      let grades = new Array();
      await cc.getGrades().then(result => {
        grades = result;
      });
    
      // 4 获取terms
      // 遍历每一个grades,然后获取下面的terms,合并到grades
      let forGrades = async function(grades) {
        for(let grade of grades){
          await cc.getTerms(grade.grade_id).then(result => {
            grade.terms = result;
          });
        }
      }
    
      await forGrades(grades);
    
      await ctx.render('cc/createContract',{
        title: 'Create Contract',
        student_id: ctx.params.id,
        types: types,
        cats: cats,
        grades: grades
      })
    }

    回复
    0
  • 取消 回复 发送