javascript mysql和promises

时间:2017-08-06 06:30:36

标签: javascript node.js

我正在处理承诺,或者至少尝试过。

以下是我的代码到目前为止的内容:

checkEmailUsername = function(mail, user) {
    return new Promise(function(resolve, reject) {
      var query;
      query = "SELECT * FROM users WHERE email = ? OR username = ?";
      return connection.query(query, [mail, user], function(err, row, fields) {
        if (err) {
          reject(err);
        }
        console.log(row.length);
        if (row.length > 0) {
          return resolve(true);
        } else {
          return resolve(false);
        }
      });
    }).then()["catch"]();
  };

问题是。如何从promise中返回解析值?

1 个答案:

答案 0 :(得分:3)

你不能在这里使用return,使用promise resolve函数将行从db返回给调用者。

    checkEmailUsername = function (mail, user) {
        return new Promise(function (resolve, reject) {
            var query;
            query = "SELECT * FROM users WHERE email = ? OR username = ?";
            connection.query(query, [mail, user], function (err, row, fields) {
                if (err) {
                    reject(err);
                }
                console.log(row.length);
                resolve(row);
            });
        };

        checkEmailUsername(mail, user).then(function (rows) {
            // do something with the rows
        }).catch((err) => {
            //handle error
        }