refactor: cache resource promises up front

This commit is contained in:
cha0s 2019-04-12 08:59:02 -05:00
parent 2d2eb62073
commit 51da538730

View File

@ -14,17 +14,19 @@ export class Resource {
this.loadCache = {};
}
if (this.loadCache[uri]) {
return Promise.resolve(JSON.parse(JSON.stringify(this.loadCache[uri])));
return this.loadCache[uri].then((json) => {
return JSON.parse(JSON.stringify(json));
});
}
if ('undefined' !== typeof window) {
return fetch(uri).then((response) => {
return this.loadCache[uri] = fetch(uri).then((response) => {
return response.json();
}).then((json) => {
return this.loadCache[uri] = json;
return json;
});
}
else {
return new Promise((resolve, reject) => {
return this.loadCache[uri] = new Promise((resolve, reject) => {
const fs = require('fs');
const path = require('path');
const resourcePath = path.resolve(process.cwd(), 'resource');
@ -32,7 +34,7 @@ export class Resource {
if (error) {
return reject(error);
}
resolve(this.loadCache[uri] = JSON.parse(buffer.toString('utf8')));
resolve(JSON.parse(buffer.toString('utf8')));
});
});
}