被拒绝的承诺是无法实现的



我试图将此方法用于非顺序承诺输出。

express .json调用成功地从API发送了201和用户对象,但是在控制台上,我得到了如下所示的未处理拒绝错误。这似乎应该由控制器中的.catch处理程序捕获。我想知道为什么会发生这种情况?

用户控件

module.exports.postUser = function (req, res, next) {
  var user = req.body.user;
  var ip = req.ip;
  userService.createUser(user, ip)
    .then(function (user) {
      res.status(201).json({"user": user.toJSON()});
    })
    .catch(function (err) {
      return next(err);
    });
};

userService

module.exports.createUser = function (user, ip) {
  var user = new Promise(function (resolve, reject) {
    return resolve(User.forge(user));
  });
  return user.then(function validateUser(user) {
    return user.validate({validatePassword: true});
  })
    .then(function hash() {
      var password = user.value().get('password');
      return hashPassword(password);
    })
    .then(function setPassword(hashedPass) {
      user.value().set('hashedPass', hashedPass);
      return user.value().save();
    })
    .then(function () {
      return user;
    });
};

输出
Unhandled rejection error: null value in column "status" violates not-null constraint
    at Connection.parseE (/Users/lukel99/webstorm-workspace/rocketwagon-postgres-kickstart/node_modules/pg/lib/connection.js:539:11)
    at Connection.parseMessage (/Users/lukel99/webstorm-workspace/rocketwagon-postgres-kickstart/node_modules/pg/lib/connection.js:366:17)
    at Socket.<anonymous> (/Users/lukel99/webstorm-workspace/rocketwagon-postgres-kickstart/node_modules/pg/lib/connection.js:105:22)
    at Socket.emit (events.js:107:17)
    at readableAddChunk (_stream_readable.js:163:16)
    at Socket.Readable.push (_stream_readable.js:126:10)
    at TCP.onread (net.js:538:20)
From previous event:
    at Client._query (/Users/lukel99/webstorm-workspace/rocketwagon-postgres-kickstart/node_modules/knex/lib/dialects/postgres/index.js:122:12)
    at Client.query (/Users/lukel99/webstorm-workspace/rocketwagon-postgres-kickstart/node_modules/knex/lib/client.js:127:24)
    at Runner.<anonymous> (/Users/lukel99/webstorm-workspace/rocketwagon-postgres-kickstart/node_modules/knex/lib/runner.js:118:24)
From previous event:
    at /Users/lukel99/webstorm-workspace/rocketwagon-postgres-kickstart/node_modules/knex/lib/runner.js:44:21
From previous event:
    at Runner.run (/Users/lukel99/webstorm-workspace/rocketwagon-postgres-kickstart/node_modules/knex/lib/runner.js:30:20)
    at QueryBuilder.Target.then (/Users/lukel99/webstorm-workspace/rocketwagon-postgres-kickstart/node_modules/knex/lib/interface.js:27:43)
    at null.<anonymous> (/Users/lukel99/webstorm-workspace/rocketwagon-postgres-kickstart/node_modules/bookshelf/lib/model.js:208:36)
    at processImmediate [as _immediateCallback] (timers.js:367:17)

最可能的原因是return user.value().save()没有返回promise,而是实现了回调。如果是这种情况,那么错误将被抛出到本机promise try/catch块之外,因此不会被捕获,而是被您的.catch()捕获。

最新更新