Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do both Promise's then & catch callbacks get called?

Tags:

I have the following code and when it's executed, it returns both "rejected" and "success":

// javascript promise var promise = new Promise(function(resolve, reject){   setTimeout(function(){reject()}, 1000) }); promise   .catch(function(){console.log('rejected')})   .then(function(){console.log('success')}); 

Could anyone explain why success is logged?

like image 561
c 2 Avatar asked Oct 16 '16 11:10

c 2


People also ask

Why then and catch both called?

catch , but still had both your then and catch called, it may be because your then had an error-throwing bug that you can't see unless you explicitly console the error in your catch . That's one of my pet-peeves with Promises absorbing errors even in strict mode.

Why do we use then in promise?

The then() method in JavaScript has been defined in the Promise API and is used to deal with asynchronous tasks such as an API call. Previously, callback functions were used instead of this function which made the code difficult to maintain.

What does then () do in JavaScript?

The then method returns a Promise which allows for method chaining. If the function passed as handler to then returns a Promise , an equivalent Promise will be exposed to the subsequent then in the method chain.

How do you use the promise and then?

The then() method returns a Promise. It takes two arguments: callback functions for the success and failure cases of the Promise. The Promise object is used for deferred and asynchronous computations. A Promise represents an operation that hasn't completed yet, but is expected in the future.


1 Answers

The then callback gets called because the catch callback is before it, not after. The rejection has already been handled by catch. If you change the the order (i.e. (promise.then(...).catch(...))), the then callback won't be executed.

MDN says that the .catch() method "returns a new promise resolving to the return value of the callback". Your catch callback doesn't return anything, so the promise is resolved with undefined value.

like image 104
Michał Perłakowski Avatar answered Oct 05 '22 02:10

Michał Perłakowski