From 84762894c86a825d9948556ce462f3930cac1775 Mon Sep 17 00:00:00 2001 From: Matthias Schiffer Date: Wed, 31 Oct 2018 15:33:52 +0100 Subject: Promisify XMLHttpRequest --- src/util.ts | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) (limited to 'src/util.ts') 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 { this.listeners.forEach((l) => l(...args)); } } + +export function get(url: string): Promise { + 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 { + return JSON.parse((await get(url)).responseText); +} -- cgit v1.2.3