我有以下代码:
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/