使用promises从MySQL node.js中选择多个数据



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

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

我可以把信息放在我的DB中,但现在我想把它拉出来并注销(我将在稍后显示它)

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

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]);
      }
    });
  });
}

这是个好主意吗?如果我想对这类函数使用承诺,我该怎么做?提前感谢任何帮助!!

我会用Bluebird。你可以用Promise"承诺"现有的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();
             }
        });
}

最新更新