【问题标题】:Promise : then vs then + catch [duplicate]承诺:then vs then + catch [重复]
【发布时间】:2016-01-21 13:40:36
【问题描述】:

以下2个代码有区别吗?

myPromise.then(function() {
    console.log('success');
}).catch(function() {
    console.log('error');
});

myPromise.then(function() {
    console.log('success');
}, function() {
    console.log('error');
});

我知道thencatch 返回新的promise 已解决或拒绝,并在回调中返回值。但是我在网上看到了这两个代码,我很好奇这两个代码之间的真正区别。

【问题讨论】:

  • 有一个非常简单的区别,fail 会在success 函数的INSTEAD 中调用,catch 会在success 函数之后调用,它也会捕获它的错误
  • @chrmcpn 如果承诺失败,那么它不会调用成功函数,对吗?所以它不会调用 if AFTER 因为它根本不会调用它,因为 promise 本身失败了?
  • @user441521 抱歉,我不是很清楚。我的意思是,如果成功回调中有错误,第一个代码会捕获它,但第二个不会。在原始承诺失败的情况下没有区别。
  • 如果没有提供 catch 将兼作第二个“then”函数,并且在两者都被使用的情况下,它将为两者进行错误捕获。 then(success,fail).catch() 将是最强大的。至少,这是我目前的理解

标签: javascript promise


【解决方案1】:

在您当前的代码中,它们的行为相同,因为console.log('success'); 不会失败。

但是,如果你写这样的东西......

myPromise.then(function() {
   // Some error may happen
   throw('An exception that would be caught');
}).catch(function() {
    console.log('error');
});
// Is the same as this, the errHandle tries to catch any unhandled error
// from previous result.
myPromise.then(func, null).then(null, errHandle);


myPromise.then(function() {
   // Some error may happen
   throw('An unhandled exception.');
}, function() {
    // This won't log the error if it happens in the 
    // some error may happen block.
    console.log('error');
});
// Is the same as this, the errHandle will handle errors from previous result,
// but it won't handle errs in func.
myPromise.then(func, errHandle)

第二种形式无法捕获该错误,而第一种形式可以。

测试片段:

// An function that may error and throw exception.
function funcThatThrows(test) {
  throw(`oops - error in test ${test}`);
}
function errHandler(exception) {
  console.log('We got an exception: ', exception);
}
// Expect: We got an exception:  oops - error in test 1
Promise.resolve(1).then(funcThatThrows).catch(errHandler);
// Is the same as below, the errHandler tries to catch any unhandled error
// from previous result.
// Expect: We got an exception:  oops - error in test 2
Promise.resolve(2).then(funcThatThrows, null).then(null, errHandler);

// If put the function and handler in the same then, the exception won't be caught.
// Expect: Uncaught (in promise) oops - error in test 3
Promise.resolve(3).then(funcThatThrows, errHandler);

【讨论】:

  • 所以如果我理解正确,如果我们不使用.catch,我们可能会错过成功处理程序抛出的错误。那么我们不应该总是使用.catch而不是使用标准的erroHandler函数,因为.catch正在做的正是errorHandler函数所做的只是它做的更多,并且还从成功中捕获错误处理程序?
  • 这取决于,如果你不在.catch中抛出另一个异常,那么promise将解析为.catch中的函数返回什么,有时我们想在其他地方处理异常,例如:let promise2 = getAPromiseThatMayThrow();,那么您可能不想从返回的 Promise 中捕获异常,而是在 promise2 捕获它,或者您仍然想捕获它,记录一些内容,然后将其丢弃,或者您使用特定的返回值指示 promise2 的处理程序上一步失败,这取决于。
  • 如果我确实希望我的承诺处理错误而不传播到其他承诺,在这种情况下我不应该总是使用.catch,因为它会做所有这些错误处理函数+是否也处理成功时抛出的任何异常?
  • 在这种情况下我会这样做。
  • JavaScript,你是什么?!
猜你喜欢
  • 2021-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-15
  • 2016-02-14
  • 2016-11-25
  • 2015-01-23
相关资源
最近更新 更多