CNode

node-mysql 获取值问题?(已解决)

问答
Lliuxufei发布于10 年前最后回复10 年前8 回复5681 浏览0 收藏

示例代码:

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)

A
alsotang#1·10 年前

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

L
liuxufei#2·10 年前
引用 alsotang把 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) {
    
  });
});
A
alsotang#4·10 年前

https://github.com/alsotang/node-lessons/tree/master/lesson4 看看这个吧。换用 eventproxy 方便点

W
welchwsy#5·10 年前
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) => {
})
W
welchwsy#6·10 年前

补充一个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) {
})
L
liuxufei#7·10 年前
引用 alsotanghttps://github.com/alsotang/node lessons/tree/master/lesson4 看看这个吧。换用 eventproxy 方便点

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

L
liuxufei#8·10 年前
引用 welchwsy这一段用async.forEachOf改写,形如:

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

参与回复
登录后即可参与回复。登录