Your code is placing the catch
handler on the promise returned from .then()
, not the original promise. If you attach them both to the original promise, you get the sequence you expect:
for (const promise of generator) {
promise.then((value) => console.log("Resolved:", value));
promise.catch((error) => console.log("Rejected:", error));
}
You'll also get an unhandled rejection error from the first promise chain (the .then()
chain. To deal with that, you can put a dummy catch on that one:
for (const promise of generator) {
promise.then((value) => console.log("Resolved:", value)).catch(_ => _);
promise.catch((error) => console.log("Rejected:", error));
}
It's a little clearer using await
(well to me it is):
(async () => {
for (const promise of generator) {
try {
console.log("Resolved:", await promise);
}
catch(e) {
console.log("Rejected:", e);
}
}})()
edit — Bergi points out that the original problem could also be solved by assigning both the resolved handler and the rejection handler in the original .then()
call:
for (const promise of generator) {
promise.then(
(value) => console.log("Resolved:", value), // happy
(error) => console.log("Rejected:", error) // not happy
);
}