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,38 +31,31 @@ class Translator {
return; return;
} }
let files = ['rules', 'tags', 'edict', 'kanjidic']; Translator.loadData('bg/data/rules.json')
if (loadEnamDict) { .then((response) => {
files = files.concat('enamdict'); this.deinflector.setRules(JSON.parse(response));
} return Translator.loadData('bg/data/tags.json');
})
const pendingLoads = []; .then((response) => {
for (let key of files) { this.tagMeta = JSON.parse(response);
pendingLoads.push(key); return Translator.loadData('bg/data/edict.json');
Translator.loadData(this.paths[key], (response) => { })
switch (key) { .then((response) => {
case 'rules': this.dictionary.addTermDict('edict', JSON.parse(response));
this.deinflector.setRules(JSON.parse(response)); return Translator.loadData('bg/data/kanjidic.json');
break; })
case 'tags': .then((response) => {
this.tagMeta = JSON.parse(response); this.dictionary.addKanjiDict('kanjidic', JSON.parse(response));
break; return loadEnamDict ? Translator.loadData('bg/data/enamdict.json') : Promise.resolve(null);
case 'kanjidic': })
this.dictionary.addKanjiDict(key, JSON.parse(response)); .then((response) => {
break; if (response !== null) {
case 'edict': this.dictionary.addTermDict('enamdict', JSON.parse(response));
case 'enamdict':
this.dictionary.addTermDict(key, JSON.parse(response));
break;
} }
pendingLoads.splice(pendingLoads.indexOf(key), 1); this.loaded = true;
if (pendingLoads.length === 0) { callback();
this.loaded = true;
callback();
}
}); });
}
} }
findTerm(text) { findTerm(text) {
@ -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) {
const xhr = new XMLHttpRequest(); return new Promise((resolve, reject) => {
xhr.addEventListener('load', () => callback(xhr.responseText)); const xhr = new XMLHttpRequest();
xhr.open('GET', chrome.extension.getURL(url), true); xhr.addEventListener('load', () => resolve(xhr.responseText));
xhr.send(); xhr.open('GET', chrome.extension.getURL(url), true);
xhr.send();
});
} }
} }