node-mysql 获取值问题?(已解决)
发布于 8 年前 作者 liuxufei 4314 次浏览 来自 问答

示例代码:

pool.getConnection(function(err, connection) {
  async.waterfall([function (cb) {
    connection.query('SELECT * FROM aaa', function(err, res_aaa) {
      cb(err, res_aaa);
    });
  }, function (res_aaa, cb) {
    for (let i = 0, l = res_aaa.length; i < l; i++) {
      connection.query('SELECT name FROM bbb WHERE id = ?', [user_id], function(err, name) {
        res_aaa[i].name = name; // name 如何才能传到外部 res_aaa?
      });
    }
    console.log(res_aaa); // 这里如何获取上面 name 的值?
    cb(err, res_aaa);
  }], function (err, result) {
    
  });
});

console.log(res_aaa); 这里的 res_aaa 怎么才能得到 name 的值?

8 回复

console.log(res_aaa); 放到下一个 function 里面去。

@alsotang

pool.getConnection(function(err, connection) {
  async.waterfall([function (cb) {
    connection.query('SELECT * FROM aaa', function(err, res_aaa) {
      cb(err, res_aaa);
    });
  }, function (res_aaa, cb) {
    for (let i = 0, l = res_aaa.length; i < l; i++) {
      connection.query('SELECT name FROM bbb WHERE id = ?', [user_id], function(err, name) {
        res_aaa[i].name = name; // name 如何才能传到外部 res_aaa?
      });
    }
    console.log(res_aaa); // 这里如何获取上面 name 的值?
    cb(err, res_aaa);
  }, function (res_aaa, cb) {
    console.log(res_aaa); // 是放这里吗?放这里也得不到 name 值
  }], function (err, result) {
    
  });
});

@alsotang 还是没找到方法

for (let i = 0, l = res_aaa.length; i < l; i++) {
      connection.query('SELECT name FROM bbb WHERE id = ?', [user_id], function(err, name) {
        res_aaa[i].name = name; // name 如何才能传到外部 res_aaa?
      });
    }

这一段用async.forEachOf改写,形如:

async.forEachOf(array, (item, key, cb) => {
}, (err, results) => {
})

补充一个sql执行的封装。

/**
 * 执行sql语句
 * @param {string} sql 执行的语句
 * @param {function} next 回调函数
 */
function sqlExecute (sql, next = function () {}) {
  pool.getConnection((err, connection) => {
    if (err) {
      next(err, null)
    } else {
      connection.query(sql, (err, rows) => {
        if (err) {
          sails.log.warn('sql err', sql)
        }
        next(err, rows)
        connection.release()
      })
    }
  })
}

以后需要执行的时候就这样子:

let sql = 'your sql';
sqlExecute(sql, function(err, rows) {
})

@alsotang 谢谢,eventproxy 的方式已会使用。你很喜欢用 eventproxy 胜过其他方式啊,cnode 也是用这个

@welchwsy 谢谢,通过 async.forEachOf 也实现了。

回到顶部