3 ms·
The change in mine is moving await into the second for loop, so that it can be caught and handled. async function showChapters(chapterURLs) { const c
by clarkdale 4y ago
The change in mine is moving await into the second for loop, so that it can be caught and handled.
async function showChapters(chapterURLs) {
const chapterPromises = chapterURLs.map(async (url) => {
const response = await fetch(url);
return response.json();
});
for (const i in chapterPromises) {
try {
appendChapter(await chapterPromises[i]));
} catch (error) {
handleChapterErrorGracefully(error, i);
}
}
}
I used for..in so that the index can be passed to handleChapterErrorGracefully
- clarkdale 4y agoHere is a way with a Generator (the chapterGenerator). Only writing this because I've seen a lot of comments lamenting lack of "streams" async function showChapters(chapterURLs) { const chapterGenerator = function*() { for(const url of chapterURLs) { yield fetch(url).then(response => response.json()); } }; for (const chapter of chapterGenerator()) { try { appendChapter(await chapter)); } catch (error) { handleChapterErrorGracefully(error); } } }
- DecoPerson 4y agoI don’t believe this will resolve the issue. - Promises are created: 1,2,3,4 - The for loop awaits promise 1 - Promise 3 is rejected - Promise 1 is resolved - The for loop awaits promise 2 - … Somewhere in this, promise 3’s rejection would be considered unhandled (I’m not sure exactly when).
- clarkdale 4y agoPromise 3's rejection would be awaited and handled after promise 2. Yes, it might finish over the network before promise 1, but it won't be realized by the program until its await occurs in the for loop.
- DecoPerson 4y agoThe issue is that V8 unhandled rejection logic doesn’t wait until the promise is awaited. If a promise is rejected, has no awaiter (.then/.catch/await), and persists in this state for some amount of time/event-loops (that the article covers), it will be treated as unhandled. I tested this in Node 18. It treats it as unhandled. The only way to avoid the gotcha’s described in the article is to ensure all promises: - cannot fail, and/or - are immediately awaited (by anything but .catch is the easiest).