太长,读不下去了不要使用.catch()或.then(成功,
)如果您不希望在发生错误后调用promise链中的后续函数。仅在链的末端捕获,以获得整个异步调用链的结果,而不会出现错误后不需要的调用。
好的,让我们假设一个函数只返回一个被拒绝的承诺:
function fakeForbiddenAsyncOperation(){
return new Promise(function(resolve , reject){
return reject('This operation is forbidden');
});
}
然后,一个承诺链如:
fakeForbiddenAsyncOperation().then(
function(){
console.log('first parameter, success');
},
function(err ){
console.log('second parameter, failure: ' + err);
})
.then(function(){
console.log('This log is called, because the previous error was catched in the second then() lambda');
})
.catch(console.log);
会让那个控制台。日志“调用此日志…”以运行,因为错误正在处理中。输出将是:
第二个参数,失败:禁止此操作
调用此日志是因为在第二个then()lambda中捕获了上一个错误
您希望在代码中执行的操作更类似于以下操作:如果验证中存在以前的错误,则防止创建用户:
fakeForbiddenAsyncOperation().then(
function(){
console.log('first parameter, success');
})
.then(function(){
console.log('This log is called');
} , function(err){
console.log('There was an err: ' + err);
console.log('this is called at the end, and the previous "this log is called" log wasn\'t fired because there was an unhandled rejection');
});
出现错误:错误:禁止此操作
这在结束时调用,之前的“此日志被调用”日志未被触发,因为存在未处理的拒绝
还有两个您可能需要处理的小问题:
Bluebird documentation
建议使用.catch()而不是.then(成功,失败):
forbiddenAsyncOperation().then(
function(){
console.log('first parameter, success');
})
.then(function(){
console.log('This log is called');
})
.catch(function(){
console.log('this is called at the end, and the previous "this log is called" log wasn\'t fired because there was an unhandled rejection');
});
将与前面的示例类似。
而且
is better to reject errors instead of strings
:
reject(new Error('The nickname must be longer than 4 and shorter than 20 characters'));
将打印错误堆栈跟踪,而不仅仅是控制台中的消息。