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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With