Javascript Promise,为什么拒绝未处理?

标签 javascript es6-promise

我有以下代码:

function validateRole(message, cmdCalled) {
  return new Promise(function(resolve, reject) {
    winston.debug('Checking user\'s role');
    Game.findOne({
      running: true,
      'players.id': message.author.id
    }, {
      'players.$': 1
    }).then(function(result) {
      console.log(result);
      if (!result) reject('playerNotFound');
      if (cmdCalled === 'vote' && result.players[0].role.match(/wolf/gi)) {
        message.author.send('Wolves are not allowed to vote!');
        reject('voteDenied');
      }
    }, reject).catch(function(err) {
      winston.debug(err);
    });
  });
}
validateRole(message,'someCommand').then(...)

如果任何条件语句失败,我会得到 error: Unhandled Rejection at: Promise Promise { <rejected> 'voteDenied' } reason: voteDenied 。为什么这不被 catch 处理?或者这是处理问题的错误方法,用 false 值或其他值解析并在 then() 函数中处理结果会更好吗?

最佳答案

因为你},拒绝)。返回的 promise 。由于 reject 返回未定义,因此 .catch 无法执行。

+不要使用 Promise 构造函数反模式。

让我们稍微清理一下,然后您可以在任何需要的地方添加日志记录。

function validateRole(message, cmdCalled) {
  return Game.findOne({
    running: true,
    'players.id': message.author.id
  }, {
    'players.$': 1
  })
  .catch(function(err){
    console.log("error", err);
    //implicitely returns undefined as the `result` into the following `.then()`
  })
  .then(function(result) {
    if (!result) 
      throw 'playerNotFound';

    if (cmdCalled === 'vote' && result.players[0].role.match(/wolf/gi)) {
      message.author.send('Wolves are not allowed to vote!');
      throw 'voteDenied';
    }
  });
  //and after this you either have a promise with a valid result,
  //or a rejected promise containing 'playerNotFound' or `voteDenied`
}

或者如果您想单独处理请求的错误

function validateRole(message, cmdCalled) {
  return Game.findOne({
    running: true,
    'players.id': message.author.id
  }, {
    'players.$': 1
  })
  .then(function(result) {
    if (!result) 
      throw 'playerNotFound';

    if (cmdCalled === 'vote' && result.players[0].role.match(/wolf/gi)) {
      message.author.send('Wolves are not allowed to vote!');
      throw 'voteDenied';
    }
  }, function(err){
    //this will catch Errors from `findOne()` but not the errors thrown in the function above
    console.log(err);
    throw 'requestFailed';
  });
  //and after this you either have a promise with a valid result,
  //or a rejected promise containing 'playerNotFound' or `voteDenied` or `requestFailed`
}

关于Javascript Promise,为什么拒绝未处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46999973/

相关文章:

javascript - 为什么更改父类为空输入?

javascript - 在处理递归时,使用 Promises 的 reduce 模式的替代方案是什么?

javascript - ES6 Promise.all 进度

javascript - 将 es6-promise polyfill 导入 Vue.js

node.js - 如何确保 Lambda 函数等待使用 wait 调用异步函数?

javascript - jQuery:将鼠标悬停在另一个 div 上时如何控制 div 的不透明度?

javascript - JQuery:将 div 附加为 var 类

javascript - Promises 传播中间对象(NodeJS + MongoDB)

javascript - 内容脚本在 Edge 扩展中不起作用

javascript - 如何将变量(实际上是一个列表)导出到类内函数中的其他 .js 文件