21 lines
590 B
TypeScript
Raw Normal View History

2018-04-16 19:41:37 +00:00
export function fetchWithProgress(url, options: RequestInit, onProgress: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null): Promise<string> {
2018-04-16 19:41:05 +00:00
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest()
2018-04-17 11:16:53 +00:00
xhr.addEventListener("load", e => resolve(xhr.responseText))
xhr.addEventListener("error", reject)
2018-04-16 19:41:05 +00:00
2018-04-17 11:16:53 +00:00
if(onProgress && xhr.upload) {
xhr.upload.addEventListener("progress", onProgress)
}
2018-04-16 19:41:05 +00:00
2018-04-17 11:16:53 +00:00
xhr.open(options.method || "GET", url)
2018-04-17 11:07:42 +00:00
2018-04-17 11:16:53 +00:00
for(let k in options.headers || {}) {
xhr.setRequestHeader(k, options.headers[k])
2018-04-16 19:41:05 +00:00
}
2018-04-16 19:41:37 +00:00
xhr.send(options.body)
2018-04-16 19:41:05 +00:00
})
}