stop holding a reference to a Promise when it is resolved (#1284)

pull/1289/head
Christophe Eymard 2023-04-03 23:23:59 +02:00 zatwierdzone przez GitHub
rodzic ae9972a91a
commit 91ffaa1a2d
Nie znaleziono w bazie danych klucza dla tego podpisu
ID klucza GPG: 4AEE18F83AFDEB23
1 zmienionych plików z 10 dodań i 4 usunięć

Wyświetl plik

@ -4,20 +4,26 @@ interface IncludeFile {
html: string;
}
const includeFiles = new Map<string, Promise<IncludeFile>>();
const includeFiles = new Map<string, IncludeFile | Promise<IncludeFile>>();
/** Fetches an include file from a remote source. Caching is enabled so the origin is only pinged once. */
export function requestInclude(src: string, mode: 'cors' | 'no-cors' | 'same-origin' = 'cors'): Promise<IncludeFile> {
if (includeFiles.has(src)) {
return includeFiles.get(src)!;
const prev = includeFiles.get(src);
if (prev !== undefined) {
// Promise.resolve() transparently unboxes prev if it was a promise.
return Promise.resolve(prev);
}
const fileDataPromise = fetch(src, { mode: mode }).then(async response => {
return {
const res = {
ok: response.ok,
status: response.status,
html: await response.text()
};
// Replace the cached promise with its result to avoid having buggy browser Promises retain memory as mentioned in #1284 and #1249
includeFiles.set(src, res);
return res;
});
// Cache the promise to only fetch() once per src
includeFiles.set(src, fileDataPromise);
return fileDataPromise;
}