Подтвердить что ты не робот

Обещание: затем vs then + catch

Существует ли какая-либо разница между двумя следующими кодами?

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

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

Я знаю, что then и catch возвращает новый promises разрешенный или отклоненный с возвратом значения в обратном вызове. Но я вижу 2 кода в Интернете, и мне интересно узнать о реальных различиях между двумя кодами.

4b9b3361

Ответ 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);

Ответ 2

Я предполагаю, что это зависит от того, как реализовано обещание. Насколько я знаю, jQuery реализует его в другой моде.

Второе, что вы дали, похоже, является версией jQuery.