Skip to content

Commit 969ec27

Browse files
[refactor] Simplify loadJSON function in translator.js
1 parent e26aed9 commit 969ec27

2 files changed

Lines changed: 13 additions & 21 deletions

File tree

CHANGELOG.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,8 @@ planned for 2025-07-01
3131
- Switch Stylelint config to flat format and simplify Stylelint scripts
3232
- [workflow] Replace Node.js version v23 with v24 (#3770)
3333
- [refactor] Replace deprecated constants `fs.F_OK` and `fs.R_OK` (#3789)
34-
- [refactor] Replace `ansis` with built-in function `util.styleText`
34+
- [refactor] Replace `ansis` with built-in function `util.styleText` (#3793)
35+
- [refactor] Simplify the `loadJSON` function in `translator.js` by replacing `XMLHttpRequest` with `fetch` (#3792)
3536

3637
### Fixed
3738

js/translator.js

Lines changed: 11 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -3,30 +3,21 @@
33
const Translator = (function () {
44

55
/**
6-
* Load a JSON file via XHR.
6+
* Load a JSON file using fetch.
77
* @param {string} file Path of the file we want to load.
88
* @returns {Promise<object>} the translations in the specified file
99
*/
1010
async function loadJSON (file) {
11-
const xhr = new XMLHttpRequest();
12-
return new Promise(function (resolve) {
13-
xhr.overrideMimeType("application/json");
14-
xhr.open("GET", file, true);
15-
xhr.onreadystatechange = function () {
16-
if (xhr.readyState === 4 && xhr.status === 200) {
17-
// needs error handler try/catch at least
18-
let fileInfo = null;
19-
try {
20-
fileInfo = JSON.parse(xhr.responseText);
21-
} catch (exception) {
22-
// nothing here, but don't die
23-
Log.error(` loading json file =${file} failed`);
24-
}
25-
resolve(fileInfo);
26-
}
27-
};
28-
xhr.send(null);
29-
});
11+
try {
12+
const response = await fetch(file);
13+
if (!response.ok) {
14+
throw new Error(`HTTP error! status: ${response.status}`);
15+
}
16+
return await response.json();
17+
} catch (error) {
18+
Log.error(`Loading json file ${file} failed: ${error.message}`);
19+
return null;
20+
}
3021
}
3122

3223
return {

0 commit comments

Comments
 (0)