搜尋

首頁  >  問答  >  主體

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,请大神指教

迷茫迷茫2785 天前683

全部回覆(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
  • 取消回覆