I emulated 3 promises - two resolved, one rejected, wrapped a try-catch function, but I still get warnings in the console: (node: 4159) UnhandledPromiseRejectionWarning: Unhandled promise rejection.
const emulate = (id, ms) =>
new Promise((resolve, reject) => {
if (ms > 1500) reject(id);
setTimeout(() => {
resolve(id);
}, ms);
});
const promises = [
emulate(1, 500),
emulate(2, 1000),
emulate(3, 2000)
];
async function stepByStepResolve() {
try {
for await (const promise of promises)
console.log(promise);
} catch (e) {
console.log('Err:', e);
}
}
stepByStepResolve();
When you call
emulate(3, 2000)
in thepromises
array, a promise is created, and will get rejected on the next phase of the event loop, except if you are listening to it and handling it, before that. Now, in thefor loop
, you are listening to all 3 promises in order, and sinceemulate(3, 2000)
is being listened to last, it would have already been rejected by the time you iterate to it.I can suggest two solutions to this:
Solution 1: Simply place
emulate(3, 2000)
as the first element in the arrayThis will allow it to be listened to, and caught before it gets rejected.
Solution 2 (this is more of a suggestion): use a generator instead of an array, like this:
This will keep the promises from being created before the
for loop
, and will the be created one by one as you iterate through the generator.