So I am wondering if this works?
S3.getObject()
.promise()
.then()
.catch() // catch error from the first then() statement
.then()
.catch() // catch error from the second then() statement
or do I need to place all 'catches' in the end? Can I have multiple catch then? Will they be fired in the order of the 'then' statements throwing errors?
It depends of your actual goals.
As a matter of fact, .then() method takes two parameters:
onFullfilled: Callback to be invoked when the promise is fulfilled.
onRejected: Callback to be invoked when the promise is rejected.
In fact, .catch(fn) is just a shorthand for .then(null, fn).
Both .then() and .catch() each return a new promise which resolves to its return value. In other words:
A resolved promise of that value if it isn't a promise.
The actual return value if it is already a promise (that will be fulfilled or rejected).
A rejected promise if the return value is a rejected promise (as previous point says) or any error is thrown.
The main reason behind the use of .then(onFullfill).catch(onReject) pattern instead of .then(onFullfill, onReject) is that, in the former (which is equivalent to .then(onFullfill).then(null, onReject)), we are chaining the onReject callback to the promise returned by first .then() instead of directly to the original promise.
The consequence of this is that if en error is thrown inside the onFullfill callback (or it returns a promise which happen to resolve to a rejected state), it will be catched by the chained .catch() too.
So, answering to your question, when you do something like:
P.then(...)
.then(...)
.then(...)
.catch(...)
;
You are chaining promises "supposing" all will go fine "and only check at the end". That is: Whenever any step fails, all subsequent .then()s are bypassed up to the next (in this case the last) .catch().
On the other hand, if you insert more .catch()s in between, you would be able to intercept rejected promises earlier and, if appropriate, solve whatever were going on and turn it into a resolved state again in order to resume the chain.
Related
I have trouble understanding the difference between putting .catch BEFORE and AFTER then in a nested promise.
Alternative 1:
test1Async(10).then((res) => {
return test2Async(22)
.then((res) => {
return test3Async(100);
}).catch((err) => {
throw "ERROR AFTER THEN";
});
}).then((res) => {
console.log(res);
}).catch((err) => {
console.log(err);
});
Alternative 2:
test1Async(10).then((res) => {
return test2Async(22)
.catch((err) => {
throw "ERROR BEFORE THEN";
})
.then((res) => {
return test3Async(100);
});
}).then((res) => {
console.log(res);
}).catch((err) => {
console.log(err);
});
The behavior of each function is as follow, test1 fail if number is <0 test2 fails if number is > 10 and test3 fails if number is not 100. In this case test2 is only failing.
I tried to run and make test2Async fail, both BEFORE and AFTER then behaves the same way and that is not executing the test3Async. Can somebody explain to me the main difference for placing catch in different places?
In each function I console.log('Running test X') in order to check if it gets executed.
This question arises because of the previous thread I posted How to turn nested callback into promise?. I figure it is a different problem and worth posting another topic.
So, basically you're asking what is the difference between these two (where p is a promise created from some previous code):
return p.then(...).catch(...);
and
return p.catch(...).then(...);
There are differences either when p resolves or rejects, but whether those differences matter or not depends upon what the code inside the .then() or .catch() handlers does.
What happens when p resolves:
In the first scheme, when p resolves, the .then() handler is called. If that .then() handler either returns a value or another promise that eventually resolves, then the .catch() handler is skipped. But, if the .then() handler either throws or returns a promise that eventually rejects, then the .catch() handler will execute for both a reject in the original promise p, but also an error that occurs in the .then() handler.
In the second scheme, when p resolves, the .then() handler is called. If that .then() handler either throws or returns a promise that eventually rejects, then the .catch() handler cannot catch that because it is before it in the chain.
So, that's difference #1. If the .catch() handler is AFTER, then it can also catch errors inside the .then() handler.
What happens when p rejects:
Now, in the first scheme, if the promise p rejects, then the .then() handler is skipped and the .catch() handler will be called as you would expect. What you do in the .catch() handler determines what is returned as the final result. If you just return a value from the .catch() handler or return a promise that eventually resolves, then the promise chain switches to the resolved state because you "handled" the error and returned normally. If you throw or return a rejected promise in the .catch() handler, then the returned promise stays rejected.
In the second scheme, if the promise p rejects, then the .catch() handler is called. If you return a normal value or a promise that eventually resolves from the .catch() handler (thus "handling" the error), then the promise chain switches to the resolved state and the .then() handler after the .catch() will be called.
So that's difference #2. If the .catch() handler is BEFORE, then it can handle the error and allow the .then() handler to still get called.
When to use which:
Use the first scheme if you want just one .catch() handler that can catch errors in either the original promise p or in the .then() handler and a reject from p should skip the .then() handler.
Use the second scheme if you want to be able to catch errors in the original promise p and maybe (depending upon conditions), allow the promise chain to continue as resolved, thus executing the .then() handler.
The other option
There's one other option to use both callbacks that you can pass to .then() as in:
p.then(fn1, fn2)
This guarantees that only one of fn1 or fn2 will ever be called. If p resolves, then fn1 will be called. If p rejects, then fn2 will be called. No change of outcome in fn1 can ever make fn2 get called or vice versa. So, if you want to make absolutely sure that only one of your two handlers is called regardless of what happens in the handlers themselves then you can use p.then(fn1, fn2).
jfriend00's answer is excellent, but I thought it would be a good idea to add the analogous synchronous code.
return p.then(...).catch(...);
is similar to the synchronous:
try {
iMightThrow() // like `p`
then()
} catch (err) {
handleCatch()
}
If iMightThrow() doesn't throw, then() will be called. If it does throw (or if then() itself throws), then handleCatch() will be called. Notice how the catch block has no control over whether or not then is called.
On the other hand,
return p.catch(...).then(...);
is similar to the synchronous:
try {
iMightThrow()
} catch (err) {
handleCatch()
}
then()
In this case, if iMightThrow() doesn't throw, then then() will execute. If it does throw, then it would be up to handleCatch() to decide if then() is called, because if handleCatch() rethrows, then then() will not be called, since the exception will be thrown to the caller immediately. If handleCatch() can gracefully handle the issue, then then() will be called.
This question already has answers here:
Why does the Promise constructor require a function that calls 'resolve' when complete, but 'then' does not - it returns a value instead?
(5 answers)
Closed 1 year ago.
So this works
new Promise(res => {
console.log("1")
res(res);
}).then(res => {
console.log("2")
}).then(res => {
console.log("3")
})
But if I exclude the res(res), it will not chain. But it chains fine afterwards without any additional res().
Why is that, why does the first block matter if it has that res() and the subsequent blocks don't need it in order to chain onwards ?
Thanks.
It chains just fine without the call to res() in that the succeeding .then() handlers are chained onto the original promise.
But, the original promise will never be resolved if you don't execute res(someValue) so therefore, it will never call your .then() handlers. At some point, you have to resolve the original promise at the start of the chain if you want any of the .then() handlers to get called. Until you call res(someValue), you have a promise chain where the head of the chain is sitting in the pending state waiting to be resolved or rejected so it can then run the rest of the chain.
But if I exclude the res(res), it will not chain. But it chains fine afterwards without any additional res().
The original promise has to be resolved before the first .then() handler will get called. From then on, just returning from a .then() handler resolves the next promise in the chain - you no longer have to manually resolve it.
From within a .then() handler, you can trigger different outcomes three different ways:
Return from the .then() handler. This resolves that chained promise and triggers its .then() handlers to get called. If you return a value, that value becomes the new resolved value of this part of the chain. If you don't return a value or there's an implicit return, then the resolved value is undefined.
Throw an exception from within the .then() handler. This will be automatically caught by the promise infrastructure and will cause this promise in the promise chain to reject - trigger any .catch() handler to get called.
Return a promise from the .then() handler. This causes the current promise in the chain to track this new promise and it will resolve or reject based on what the newly returned promise does.
Also, a given promise can only be resolved or rejected once. It's a one-way state machine. Once it has been resolved or rejected, it's state is fixed and can not be changed again. So, you would only ever call res(someValue) once. Attempting to call it more than once just does nothing as the promise has already been changed to the fulfilled state and can no longer be changed.
FYI, the three states of a promise are pending, fulfilled and rejected. When you call res(someValue), you change the state of the original promise in your chain from pending to fulfilled and the internals of the promise will then call its .then() handlers on the next tick.
Something that people often don't realize is that each call to .then() creates and returns a new promise that is linked to the earlier promise chain. So, the code in your question actually creates 3 promises, one from new Promise() and two from the two calls to .then(). These subsequent promises from calls to .then() get resolved or rejected only when the parent promise gets resolved or rejected and the .then() or .catch() handler gets called and then there's a return value from that .then() or .catch() handler. Those return values from those handlers determine what happens next in the chain.
I'm wanting to clarify how a promise is passed to .catch and what .catch does with it.
Using this as an example:
function fetchDog(){
fetch("https://dog.ceo/api/breeds/image/fail")
.then(response => response.json())
.then(data => console.log(data))
.catch(function(err) {
console.log('Fetch problem');
});
};
fetchDog();
Looking at this statement from MDN:
If the Promise that then is called on adopts a state (fulfillment or
rejection) for which then has no handler, a new Promise is created
with no additional handlers, simply adopting the final state of the
original Promise on which then was called.
I translate that to mean, in my example, the .thens return a new promise that is a copy of the promise that .then was called on.
By the time it reaches .catch, I know that .catch prints something to the console. The spec also says it behaves the same as calling Promise.prototype.then(undefined, onRejected).
Therefore, based on this excerpt from the .then spec:
If a handler function: doesn't return anything, the promise returned
by then gets resolved with an undefined value.
I expect .catch to return a new promise that 'gets resolved with' an undefined value. (What exactly does that mean, for a promise object to get 'resolved with' an undefined value)?
Is this true?
.then() calls its callback when the promise is resolved. .catch() only calls its callback when the promise is rejected.
If fetch() is successful, it resolves its promise, so only the .then() callbacks are called.
If fetch() gets an error, it rejects its promise, and the .catch() callbacks will be called. Also, if response.json() gets an error (e.g. the response was not valid JSON), it will reject the promise, and .catch() will call its callback.
I know that Promises in JS are Immutable.
According to: What does it mean for promises to be immutable and their guaranteed value?
A promise is a one-way latch. Once it is resolved with a value or
rejected with a reason, its state and value/reason can never change.
So, no matter how many times you do .then() on the same promise, you
will always get the same result.
So I am confused about this image from: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
It looks like after the Promise is either fulfilled or rejected (resolved) it returns a Promise that is (pending). Why is that?
Every call to .then() or .catch() returns a new promise. That promise will be resolved or rejected depending upon what happens in the .then() or .catch() handler that it derives from when that handler is called. The promise at the start of the chain is indeed immutable, but once someone else calls .then() or .catch() on it, they get a new promise back from each of those calls whose state is determined by what happens inside the code that runs in the .then() or .catch() handler.
When you get that new promise from .then() or .catch() it will always be in the pending state because the code inside the .then() or .catch() has not yet been called (the original promise has not yet called them). Those statements just register handlers on the original promise.
When those handlers are called, they will determine the state of the new promise. If they return a plain value, that new promise will be resolved with that value. If they throw, that new promise will be rejected. If they return a promise, then that new promise will follow the eventual state of that new promise that was returned form the .then() or .catch() handler and it will resolve or reject as that returned promise does.
I have trouble understanding the difference between putting .catch BEFORE and AFTER then in a nested promise.
Alternative 1:
test1Async(10).then((res) => {
return test2Async(22)
.then((res) => {
return test3Async(100);
}).catch((err) => {
throw "ERROR AFTER THEN";
});
}).then((res) => {
console.log(res);
}).catch((err) => {
console.log(err);
});
Alternative 2:
test1Async(10).then((res) => {
return test2Async(22)
.catch((err) => {
throw "ERROR BEFORE THEN";
})
.then((res) => {
return test3Async(100);
});
}).then((res) => {
console.log(res);
}).catch((err) => {
console.log(err);
});
The behavior of each function is as follow, test1 fail if number is <0 test2 fails if number is > 10 and test3 fails if number is not 100. In this case test2 is only failing.
I tried to run and make test2Async fail, both BEFORE and AFTER then behaves the same way and that is not executing the test3Async. Can somebody explain to me the main difference for placing catch in different places?
In each function I console.log('Running test X') in order to check if it gets executed.
This question arises because of the previous thread I posted How to turn nested callback into promise?. I figure it is a different problem and worth posting another topic.
So, basically you're asking what is the difference between these two (where p is a promise created from some previous code):
return p.then(...).catch(...);
and
return p.catch(...).then(...);
There are differences either when p resolves or rejects, but whether those differences matter or not depends upon what the code inside the .then() or .catch() handlers does.
What happens when p resolves:
In the first scheme, when p resolves, the .then() handler is called. If that .then() handler either returns a value or another promise that eventually resolves, then the .catch() handler is skipped. But, if the .then() handler either throws or returns a promise that eventually rejects, then the .catch() handler will execute for both a reject in the original promise p, but also an error that occurs in the .then() handler.
In the second scheme, when p resolves, the .then() handler is called. If that .then() handler either throws or returns a promise that eventually rejects, then the .catch() handler cannot catch that because it is before it in the chain.
So, that's difference #1. If the .catch() handler is AFTER, then it can also catch errors inside the .then() handler.
What happens when p rejects:
Now, in the first scheme, if the promise p rejects, then the .then() handler is skipped and the .catch() handler will be called as you would expect. What you do in the .catch() handler determines what is returned as the final result. If you just return a value from the .catch() handler or return a promise that eventually resolves, then the promise chain switches to the resolved state because you "handled" the error and returned normally. If you throw or return a rejected promise in the .catch() handler, then the returned promise stays rejected.
In the second scheme, if the promise p rejects, then the .catch() handler is called. If you return a normal value or a promise that eventually resolves from the .catch() handler (thus "handling" the error), then the promise chain switches to the resolved state and the .then() handler after the .catch() will be called.
So that's difference #2. If the .catch() handler is BEFORE, then it can handle the error and allow the .then() handler to still get called.
When to use which:
Use the first scheme if you want just one .catch() handler that can catch errors in either the original promise p or in the .then() handler and a reject from p should skip the .then() handler.
Use the second scheme if you want to be able to catch errors in the original promise p and maybe (depending upon conditions), allow the promise chain to continue as resolved, thus executing the .then() handler.
The other option
There's one other option to use both callbacks that you can pass to .then() as in:
p.then(fn1, fn2)
This guarantees that only one of fn1 or fn2 will ever be called. If p resolves, then fn1 will be called. If p rejects, then fn2 will be called. No change of outcome in fn1 can ever make fn2 get called or vice versa. So, if you want to make absolutely sure that only one of your two handlers is called regardless of what happens in the handlers themselves then you can use p.then(fn1, fn2).
jfriend00's answer is excellent, but I thought it would be a good idea to add the analogous synchronous code.
return p.then(...).catch(...);
is similar to the synchronous:
try {
iMightThrow() // like `p`
then()
} catch (err) {
handleCatch()
}
If iMightThrow() doesn't throw, then() will be called. If it does throw (or if then() itself throws), then handleCatch() will be called. Notice how the catch block has no control over whether or not then is called.
On the other hand,
return p.catch(...).then(...);
is similar to the synchronous:
try {
iMightThrow()
} catch (err) {
handleCatch()
}
then()
In this case, if iMightThrow() doesn't throw, then then() will execute. If it does throw, then it would be up to handleCatch() to decide if then() is called, because if handleCatch() rethrows, then then() will not be called, since the exception will be thrown to the caller immediately. If handleCatch() can gracefully handle the issue, then then() will be called.