Promisify XMLHttpRequest
This commit is contained in:
parent
68ff0cb4b1
commit
84762894c8
2 changed files with 38 additions and 11 deletions
16
src/index.ts
16
src/index.ts
|
@ -1,23 +1,17 @@
|
|||
import MapData from './model/data/MapData';
|
||||
|
||||
import { getJSON } from './util';
|
||||
import { loadMap } from './view/map';
|
||||
import Renderer from './view/renderer/Renderer';
|
||||
|
||||
window.onload = () => {
|
||||
window.onload = async () => {
|
||||
const canvas = document.getElementById('rpgedit') as HTMLCanvasElement;
|
||||
if (!canvas)
|
||||
return;
|
||||
|
||||
const renderer = new Renderer(canvas);
|
||||
|
||||
const xhr = new XMLHttpRequest();
|
||||
|
||||
xhr.addEventListener('load', async function() {
|
||||
const map = new MapData(JSON.parse(this.responseText));
|
||||
const mapView = await loadMap(renderer, map);
|
||||
mapView.render();
|
||||
});
|
||||
|
||||
xhr.open('GET', 'resources/map/test.json', true);
|
||||
xhr.send();
|
||||
const map = new MapData(await getJSON('resources/map/test.json'));
|
||||
const mapView = await loadMap(renderer, map);
|
||||
mapView.render();
|
||||
};
|
||||
|
|
33
src/util.ts
33
src/util.ts
|
@ -45,3 +45,36 @@ export class Listenable<T extends any[]> {
|
|||
this.listeners.forEach((l) => l(...args));
|
||||
}
|
||||
}
|
||||
|
||||
export function get(url: string): Promise<XMLHttpRequest> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const xhr = new XMLHttpRequest();
|
||||
|
||||
const handleError = () => {
|
||||
if (xhr.readyState !== xhr.DONE) {
|
||||
reject(new Error('HTTP request ended in state ' + xhr.readyState));
|
||||
return;
|
||||
}
|
||||
|
||||
reject(new Error('HTTP request returned status ' + xhr.status));
|
||||
};
|
||||
|
||||
xhr.addEventListener('error', handleError);
|
||||
|
||||
xhr.addEventListener('load', () => {
|
||||
if (xhr.readyState !== xhr.DONE || xhr.status !== 200) {
|
||||
handleError();
|
||||
return;
|
||||
}
|
||||
|
||||
resolve(xhr);
|
||||
});
|
||||
|
||||
xhr.open('GET', url, true);
|
||||
xhr.send();
|
||||
});
|
||||
}
|
||||
|
||||
export async function getJSON(url: string): Promise<any> {
|
||||
return JSON.parse((await get(url)).responseText);
|
||||
}
|
||||
|
|
Reference in a new issue