In your first example, promise2
is the result of calling:
const promise2 = axios.get(...).then(...).catch(...)
And, it's a new promise, different from just what axios.get()
returns and it is NOT resolved until AFTER the .catch()
or .then()
handler runs because its resolved value or rejected reason is determined by what happens in the .then()
or .catch()
handler.
Each step in the chain returns a new promise that isn't resolved until every before it in the chain has resolved and until this particular handler has been executed (or bypassed).
So, in this chain:
const promise2 = axios.get(...).then(...).catch(...)
You get the first promise from axios.get()
, then another one from .then()
, then another one from .catch()
and promise2
will be contain the final one from the .catch()
. That final promise will not resolve or reject until the whole chain is done.
In your second example, promise2
is only the result of calling:
const promise2 = axios.get()
So, the promise2
value is known as soon as the axios()
call is done and will be known by the time the .then()
or .catch()
handler is called in this:
promise2.then().catch()
P.S. I would appreciate if someone could point me (in the comments) to the rationale why these methods return new objects and what I could do with those new objects.
It has to do with how promise chaining works. In order to implement chaining of multiple .then()
handlers where each of those handlers could themselves contain functions that return new promises, you need to create intermediate promises in the chain that are dependent on things that happen later in the chain.
Here are a few other relevant answers:
Understanding javascript promises; stacks and chaining
What is the order of execution in javascript promises
Is there a difference between promise.then.then vs promise.then; promise.then
You don't typically do anything with the intermediate promise objects yourself, they are mostly there to make promise chaining work properly. You would normally just do:
axios.get(...).then(...).catch(...)
and not assign any of the promises to any variables.