Simplify loading code with promises

This commit is contained in:
Alex Yatskov 2016-08-08 09:09:03 -07:00
parent 6c838b7fb4
commit afef392491

View File

@ -19,14 +19,6 @@
class Translator { class Translator {
constructor() { constructor() {
this.paths = {
rules: 'bg/data/rules.json',
tags: 'bg/data/tags.json',
edict: 'bg/data/edict.json',
enamdict: 'bg/data/enamdict.json',
kanjidic: 'bg/data/kanjidic.json'
};
this.loaded = false; this.loaded = false;
this.tagMeta = null; this.tagMeta = null;
this.dictionary = new Dictionary(); this.dictionary = new Dictionary();
@ -39,39 +31,32 @@ class Translator {
return; return;
} }
let files = ['rules', 'tags', 'edict', 'kanjidic']; Translator.loadData('bg/data/rules.json')
if (loadEnamDict) { .then((response) => {
files = files.concat('enamdict');
}
const pendingLoads = [];
for (let key of files) {
pendingLoads.push(key);
Translator.loadData(this.paths[key], (response) => {
switch (key) {
case 'rules':
this.deinflector.setRules(JSON.parse(response)); this.deinflector.setRules(JSON.parse(response));
break; return Translator.loadData('bg/data/tags.json');
case 'tags': })
.then((response) => {
this.tagMeta = JSON.parse(response); this.tagMeta = JSON.parse(response);
break; return Translator.loadData('bg/data/edict.json');
case 'kanjidic': })
this.dictionary.addKanjiDict(key, JSON.parse(response)); .then((response) => {
break; this.dictionary.addTermDict('edict', JSON.parse(response));
case 'edict': return Translator.loadData('bg/data/kanjidic.json');
case 'enamdict': })
this.dictionary.addTermDict(key, JSON.parse(response)); .then((response) => {
break; this.dictionary.addKanjiDict('kanjidic', JSON.parse(response));
return loadEnamDict ? Translator.loadData('bg/data/enamdict.json') : Promise.resolve(null);
})
.then((response) => {
if (response !== null) {
this.dictionary.addTermDict('enamdict', JSON.parse(response));
} }
pendingLoads.splice(pendingLoads.indexOf(key), 1);
if (pendingLoads.length === 0) {
this.loaded = true; this.loaded = true;
callback(); callback();
}
}); });
} }
}
findTerm(text) { findTerm(text) {
const groups = {}; const groups = {};
@ -254,10 +239,12 @@ class Translator {
return code >= 0x4e00 && code < 0x9fb0 || code >= 0x3400 && code < 0x4dc0; return code >= 0x4e00 && code < 0x9fb0 || code >= 0x3400 && code < 0x4dc0;
} }
static loadData(url, callback) { static loadData(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest(); const xhr = new XMLHttpRequest();
xhr.addEventListener('load', () => callback(xhr.responseText)); xhr.addEventListener('load', () => resolve(xhr.responseText));
xhr.open('GET', chrome.extension.getURL(url), true); xhr.open('GET', chrome.extension.getURL(url), true);
xhr.send(); xhr.send();
});
} }
} }