Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promise : then vs then + catch [duplicate]

People also ask

What is then and catch in promise?

In summary: then : when a promise is successful, you can then use the resolved data. catch : when a promise fails, you catch the error, and do something with the error information. finally : when a promise settles (fails or passes), you can finally do something.

Is catch a promise?

catch() The catch() method returns a Promise and deals with rejected cases only. It behaves the same as calling Promise.

Does promise reject to catch?

catch doesn't trigger at all. But if any of the promises above rejects (a network problem or invalid json or whatever), then it would catch it.

Does a promise need a then?

You can think of a promise as a placeholder for a value that hasn't been computed yet. However, there's no way to get a promise's value from the promise directly - you need to call the then() function to register a callback that JavaScript will call when the value is computed.


In your current code, they act the same because console.log('success'); will not fail.

However, if you write something like this...

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)

The second form can't catch that error, while the first can.

Snippet for test:

// 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);