node.js - node中MYSQL的异步问题
迷茫
迷茫 2017-04-17 16:32:45
0
1
681

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

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(1)
Peter_Zhu
rows.forEach(function(row){
   console.log(row);
});

The loop here is asynchronous, so if something goes wrong, you need to control the asynchronousness.

Let me give you an example. I just learned to write, so I’m not very good at writing, but I can show you how to control asynchronousness.

这里是引用的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
  })
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template