Skip to content

Commit

Permalink
fix: race condition in declaration-data.js
Browse files Browse the repository at this point in the history
  • Loading branch information
hargoniX committed Jul 20, 2023
1 parent 9af4c72 commit 5ce54e8
Showing 1 changed file with 25 additions and 17 deletions.
42 changes: 25 additions & 17 deletions static/declaration-data.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export class DeclarationDataCenter {
* Used to implement the singleton, in case we need to fetch data mutiple times in the same page.
*/
static singleton = null;
static requestSingleton = null;

/**
* Construct a DeclarationDataCenter with given data.
Expand All @@ -41,28 +42,35 @@ export class DeclarationDataCenter {
* @returns {Promise<DeclarationDataCenter>}
*/
static async init() {
if (!DeclarationDataCenter.singleton) {
const dataListUrl = new URL(
`${SITE_ROOT}/declarations/declaration-data.bmp`,
window.location
);

// try to use cache first
const data = await fetchCachedDeclarationData().catch(_e => null);
if (data) {
// if data is defined, use the cached one.
DeclarationDataCenter.singleton = new DeclarationDataCenter(data);
} else {
// undefined. then fetch the data from the server.
const dataListRes = await fetch(dataListUrl);
const data = await dataListRes.json();
await cacheDeclarationData(data);
DeclarationDataCenter.singleton = new DeclarationDataCenter(data);
if (DeclarationDataCenter.singleton === null) {
if (DeclarationDataCenter.requestSingleton === null) {
DeclarationDataCenter.requestSingleton = DeclarationDataCenter.getData();
}
await DeclarationDataCenter.requestSingleton;
}
return DeclarationDataCenter.singleton;
}

static async getData() {
const dataListUrl = new URL(
`${SITE_ROOT}/declarations/declaration-data.bmp`,
window.location
);

// try to use cache first
const data = await fetchCachedDeclarationData().catch(_e => null);
if (data) {
// if data is defined, use the cached one.
DeclarationDataCenter.singleton = new DeclarationDataCenter(data);
} else {
// undefined. then fetch the data from the server.
const dataListRes = await fetch(dataListUrl);
const data = await dataListRes.json();
await cacheDeclarationData(data);
DeclarationDataCenter.singleton = new DeclarationDataCenter(data);
}
}

/**
* Search for a declaration.
* @returns {Array<any>}
Expand Down

0 comments on commit 5ce54e8

Please sign in to comment.