【问题标题】:SELECT multiple data from MySQL node.js with promises使用承诺从 MySQL node.js 中选择多个数据
【发布时间】:2017-03-31 06:45:49
【问题描述】:

promise 的概念对我来说是非常新的(到目前为止,我使用的是 async.each 和 async.waterfall) 我想使用 Promise,但我现在卡住了。

我想从我的数据库中获取“标签”。 我为此有两个表:一个称为“标签”,其中包含每个标签(带有 ID),另一个称为“user_tags”,其中保存了每个用户名以及用户(用户名)创建并保存到“标签”中的标签的 ID '。

我可以将信息放入我的数据库中,但现在我想将其取出并注销(稍后我将显示它)

到目前为止,这是我的想法:

var getUserprofile = function getUserprofile(username, callback){
  pool.getConnection(function (err, connection) {
    var dataUser = [];

    // Error check
    if (err) {
      console.log(err);
    }

    connection.query('SELECT * FROM users_tags FULL JOIN tags ON (tags.id = users_tags.t_id) WHERE users_tags.user_id=666;', username , function (err, rows, fields) {
      if (err) {
        connection.release();
        cb(err);
      } else if (rows.length < 1) {
        connection.release();
        cb("We don't have any informations about this user yet");

      } else {
        console.log("we pull the information right now");
        connection.release();
        callback(null, rows[0]);
      }
    });
  });
}

这是个好主意吗?如果我想对这种功能使用 Promise,我该怎么办? 在此先感谢您的帮助!!!

【问题讨论】:

    标签: javascript mysql node.js promise


    【解决方案1】:

    我会使用Bluebird。您可以使用 Promise.promisify 或 Promise.promisifyAll“承诺”现有 API。

    我会做类似的事情

    var Promise = require('bluebird'),
         ... //other deps;
    
    var pool = Promise.promisifyAll(pool);
    function getUserprofile(username){
        var connection = null;
        return pool.getConnectionAsync()
            .then(function (conn) {
                 connection = Promise.promisifyAll(conn);
                 return connection.queryAsync('...');
            })
            .then(function (results) {
                 if (results.length < 1) {
                     return "We don't have any informations about this user yet";
                 } else {
                     console.log("we pull the information right now");
                     return results[0];
                 }
            })
            .catch(function (err) {
                 console.log(err);
                 throw err;
            })
            .finally(function () {
                 if (connection) {
                     connection.release();
                 }
            });
    }
    

    【讨论】:

    • 您好,感谢您的帮助,对蓝鸟一无所知。我现在正在检查它。但是您的回答对我来说有些奇怪,您与数据库的连接看起来根本不像我的。我真的不明白。这是必须的 ?那为什么我的不好呢?谢谢你的回答。
    • 我只是使用 API 的承诺版本 (getConnectionAsync) 来创建连接。你有什么困扰?
    • 我一直在我所有的项目中使用这个“pool.getConnection(function (err, connection)”方法,如果我开始使用(getConnectionAsync)方法,这意味着我必须改变所有到目前为止我的请求对吗?我已经声明了一个 var 池。
    • 好吧,这取决于你。例如,您可以仅将承诺版本用于您的连接(queryAsync),但在两种情况下(池和连接)都使用承诺不是更好吗? ;)
    • 好吧,我没有承诺就做到了。我不得不使用 async.each 来循环我的 [] 并且它可以工作。我保留您的示例,因为无论如何我在其他地方都需要它。我想将它们用于我的下一个功能,即 getUserPictures。非常感谢您的帮助。
    猜你喜欢
    • 2017-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-15
    相关资源
    最近更新 更多