承诺:那么vs那么+赶上

Mag*_*gus 91 javascript promise

以下2个代码有什么区别吗?

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

myPromise.then(function() {
    console.log('success');
}, function() {
    console.log('error');
});
Run Code Online (Sandbox Code Playgroud)

我知道thencatch通过回调中的值返回返回已解决或拒绝的新promise.但我看到网络上的2个代码,我很好奇2代码之间的真正差异.

fuy*_*oya 138

在您当前的代码中,它们的行为相同,因为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)
Run Code Online (Sandbox Code Playgroud)

第二种形式无法捕获该错误,而第一种形式则无法捕获.

测试片段:

// 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);
Run Code Online (Sandbox Code Playgroud)

  • JavaScript,你是什么?! (5认同)
  • 因此,如果我正确理解如果不使用.catch,那么我们可能会错过成功处理程序抛出的错误。那么我们不应该总是使用.catch而不是标准的erroHandler函数,因为.catch确实在执行errorHandler函数所做的事情,它只会做更多的事情,而且还会从成功处理程序中捕获错误? (2认同)
  • 这取决于,如果您不在`.catch`中抛出另一个异常,则promise将解析为..catch`中的函数返回什么,有时我们想在其他地方处理异常,例如:`let promise2 = getAPromiseThatMayThrow();`,那么您可能不希望从返回的promise中捕获异常,而是在`promise2`处捕获它,或者您仍想捕获它,记录某些内容,然后将其丢弃,或者使用特定的返回值指示上一步失败的`promise2`处理程序,这取决于。 (2认同)
  • 如果我确实希望我的诺言处理错误并且不传播到其他诺言,在这种情况下,我不应该总是使用`.catch`,因为它会执行所有错误处理功能,并且还可以处理任何异常抛出成功? (2认同)