summaryrefslogtreecommitdiffstats
path: root/src/util.ts
diff options
context:
space:
mode:
authorMatthias Schiffer <mschiffer@universe-factory.net>2018-10-31 15:33:52 +0100
committerMatthias Schiffer <mschiffer@universe-factory.net>2018-10-31 15:33:52 +0100
commit84762894c86a825d9948556ce462f3930cac1775 (patch)
tree1a6a09f5dc98a9cda89838fa3fb783645a7c37f2 /src/util.ts
parent68ff0cb4b1f5e8d354282ef988fcb42240e34d1b (diff)
downloadrpgedit-84762894c86a825d9948556ce462f3930cac1775.tar
rpgedit-84762894c86a825d9948556ce462f3930cac1775.zip
Promisify XMLHttpRequest
Diffstat (limited to 'src/util.ts')
-rw-r--r--src/util.ts33
1 files changed, 33 insertions, 0 deletions
diff --git a/src/util.ts b/src/util.ts
index 7129b2b..29c707e 100644
--- a/src/util.ts
+++ b/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);
+}