Node Express链接函数返回UnhandledPromiseRejectionWarning

时间:2018-02-12 01:05:07

标签: javascript node.js express

我打破了一个节点端点,以便发生两件事

  1. 检查用户是否存在
  2. 将用户添加到数据库
  3. controller.js

    exports.signup = (req, res) => {
      methods.checkUser('email', req.body.email)
        .then(methods.addUser(req.body.email, req.body.password))
        .then(() => {
          res.send('added');
        })
        .catch((err) => {
          console.log(err);
          res.status(403).send(err);
        });
    };
    

    methods.js

    exports.checkUser = (key, val) => {
      return new Promise((resolve, reject) => {
        db.query('SELECT * FROM ?? WHERE ?? = ?', ['users', key, val], (err, result) => {
          if (result) {
            resolve(result);
          } else {
            reject(err);
          }
    
        });
      });
    };
    
    exports.addUser = (email, password) => {
      return new Promise((resolve, reject) => {
        if (email === 'test@domain.com') {
          resolve(true);
        } else {
          console.log('rejecting');
          reject(email);
        }
      });
    };
    

    addUser()目前只检查电子邮件=== test@domain.com是否会测试Promise链。

    因此端点在Postman中返回added

    但终端显示以下内容

    rejecting
    (node:71904) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): bot@domain.com
    (node:71904) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
    

    通常我会这样写。

    exports.signup = (req, res) => {
      methods.checkUser('email', req.body.email)
        .then(() => {
          methods.addUser(req.body.email, req.body.password)
            .then(() => {
              res.send('added');
            })
            .catch((err) => {
              res.status(403).send(err);
            })
        })
        .catch((err) => {
          console.log(err);
          res.status(403).send(err);
        });
    };
    

    我想采取更清洁的方法,但需要帮助

1 个答案:

答案 0 :(得分:1)

这是编写Promise链的正确方法:

exports.signup = (req, res) => {
    methods.checkUser('email', req.body.email)
      .then(() => methods.addUser(req.body.email, req.body.password) )
      .then(() => res.send('added') )
      .catch((err) => {
        console.log(err);
        res.status(403).send(err);
      });
  };

因此,如果链中有reject,就像示例中email=bot@domain.com输入的情况一样,拒绝将由最后catch处理。