Skip to content

Commit 46b3f25

Browse files
committed
Do not retry aborted requests and always handle promise rejection
When a network request is aborted through an external signal, it does not make any sense to retry it. Also, pending request promises were being (correctly) rejected when the request failed, but when no one was actually interested in that request, this means that the rejected promise went unhandled, leading to Node.js issuing an "UnhandledPromiseRejectionWarning" message to the console.
1 parent f205850 commit 46b3f25

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

fetch-filecache.js

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -265,7 +265,7 @@ async function fetch(url, options) {
265265
}
266266

267267
/**
268-
* Create a pending fetch promise and keep controls over that promise so that
268+
* Create a pending fetch promise and keep control over that promise so that
269269
* the code may resolve or reject it through calls to resolvePendingFetch and
270270
* rejectPendingFetch functions
271271
*/
@@ -277,6 +277,11 @@ async function fetch(url, options) {
277277
reject = innerReject;
278278
});
279279
pendingFetches[url] = { promise, resolve, reject };
280+
281+
// Make sure that we catch rejection (in case no one is actually looking
282+
// for this URL at the same time, otherwise Node.js will complain with an
283+
// "UnhandledPromiseRejectionWarning" message)
284+
promise.catch(err => {});
280285
}
281286

282287
function resolvePendingFetch(url) {
@@ -376,10 +381,10 @@ async function fetch(url, options) {
376381
return await baseFetch(url, options);
377382
}
378383
catch (err) {
379-
if (remainingAttempts <= 0) throw err;
384+
if ((err.name === 'AbortError') || (remainingAttempts <= 0)) throw err;
380385
log('fetch attempt failed, sleep and try again');
381386
await sleep(2000 + Math.floor(Math.random() * 8000));
382-
return fetchWithRetry(url, options, remainingAttempts - 1);
387+
return await fetchWithRetry(url, options, remainingAttempts - 1);
383388
}
384389
}
385390

@@ -409,7 +414,7 @@ async function fetch(url, options) {
409414
return response;
410415
}
411416
else {
412-
resolvePendingFetch(url);
417+
resolvePendingFetch(url, 'test');
413418
return readFromCache();
414419
}
415420
}

0 commit comments

Comments
 (0)