Skip to content

Commit a8a5124

Browse files
authored
Merge pull request #64 from xiCO2k/fix/concurrential-load-async
fix: Concurrentials `loadLanguageAsync` abort previous.
2 parents 7483b4f + 79efdbb commit a8a5124

File tree

1 file changed

+21
-4
lines changed

1 file changed

+21
-4
lines changed

src/index.ts

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,9 @@ export class I18n {
128128
// Stores messages for the currently active language
129129
private activeMessages: object = reactive({})
130130

131+
// Stores the abort controller for the load promises.
132+
private abortController: AbortController;
133+
131134
/**
132135
* Creates a new instance of the I18n class, applying default options
133136
*/
@@ -177,15 +180,28 @@ export class I18n {
177180
/**
178181
* Loads the language file.
179182
*/
180-
async loadLanguageAsync(lang: string, dashLangTry = false): Promise<string | void> {
183+
loadLanguageAsync(lang: string, dashLangTry = false, ignoreAbort = false): Promise<string | void> {
184+
if (! ignoreAbort) {
185+
this.abortController?.abort();
186+
this.abortController = new AbortController();
187+
}
188+
181189
const loadedLang: LanguageInterface = I18n.loaded.find((row) => row.lang === lang)
182190

183191
if (loadedLang) {
184192
return Promise.resolve(this.setLanguage(loadedLang))
185193
}
186194

187-
const { default: messages } = await this.resolveLangAsync(this.options.resolve, lang)
188-
return this.applyLanguage(lang, messages, dashLangTry, this.loadLanguageAsync)
195+
return new Promise((resolve, reject) => {
196+
this.abortController.signal.addEventListener('abort', () => {
197+
resolve();
198+
});
199+
200+
this.resolveLangAsync(this.options.resolve, lang).then(({ default: messages }) => {
201+
resolve(this.applyLanguage(lang, messages, dashLangTry, this.loadLanguageAsync));
202+
});
203+
});
204+
189205
}
190206

191207
/**
@@ -253,12 +269,13 @@ export class I18n {
253269
return callable.call(
254270
this,
255271
lang.replace(/[-_]/g, (char) => (char === '-' ? '_' : '-')),
272+
true,
256273
true
257274
)
258275
}
259276

260277
if (lang !== this.options.fallbackLang) {
261-
return callable.call(this, this.options.fallbackLang)
278+
return callable.call(this, this.options.fallbackLang, false, true)
262279
}
263280
}
264281

0 commit comments

Comments
 (0)