@mtf
Further to what @ran16 has already raised in this post in the topic for the previous exercise 8. Chaining Multiple Promises , I’ve turned this over and over and also looked at some additional documentation and other articles about the subject; but I still don’t fully understand why the lesson suggests that it’s a mistake not to explicity return the new promise with the return
keyword in chained .then()
methods, as follows:
checkInventory(order)
.then((resolvedValueArray) => {
return processPayment(resolvedValueArray);
})
.then((resolvedValueArray) => {
return shipOrder(resolvedValueArray);
})
.then((successMessage) => {
console.log(successMessage);
})
.catch((errorMessage) => {
console.log(errorMessage);
});
… because, if the first two promises resolve to fulfilled, the new promises with the new resolved array values (and not the default promise) are still clearly returned by the first two .then()
methods when the return
keyword is omitted, as follows:
/* With arrow function syntax, the single parameters in each success
handler function don't need parentheses, so I've also removed these. */
checkInventory(order)
.then(resolvedValueArray => processPayment(resolvedValueArray))
.then(resolvedValueArray => shipOrder(resolvedValueArray))
.then( /* same as before */ )
.catch( /* same as before */ );
Does this work because the functions called in the success handlers already return the next promises? e.g.
const processPayment = (responseArray) => {
...
return new Promise ((resolve, reject) => { // promise returned here
...
if ..... resolve([order, trackingNum]);
else ... reject(`Cannot process order ...`);
});
};
Are we being taught to always use the keyword return
in .then()
when chaining promises, in order to make sure our code also accounts for situations when the next promise won’t have already been returned, as in our example? (…although I haven’t come up with an alternative example of when that would actually happen.)
The correct new promises are also returned by the first two .then()
methods with the following even more concise version:
checkInventory(order)
.then(processPayment)
.then(shipOrder)
.then( /* same as before */ )
.catch( /* same as before */ );
I’m assuming that we can also omit the resolved value parameters in the first two .then
methods, as the functions processPayment
and shipOrder
are themselves the success handlers, and so there is no need to reproduce the success handlers within .then()
but, instead, it is enough to simply reference them via their function names.
Have I understood correctly what is happening here?
Is the last alternative version above an improvement, because it’s more concise but still robust? … or is it cutting corners which, although maybe not causing any problems in this example, could cause maintenance/sustainability issues if the program were to be developed further?