Last active
February 10, 2019 22:25
-
-
Save justsml/a8ffd810fc7e5a5295dfc898302ddbfc to your computer and use it in GitHub Desktop.
Adds an onProgress mechanism to track Download Progress when using the `fetch` API.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function progressHelper(onProgress) { | |
return (response) => { | |
if (!response.body) return response | |
let loaded = 0 | |
const contentLength = response.headers.get('content-length') | |
const total = !contentLength ? -1 : parseInt(contentLength, 10) | |
return new Response( | |
new ReadableStream({ | |
start(controller) { | |
const reader = response.body.getReader() | |
return read() | |
function read() { | |
return reader.read() | |
.then(({ done, value }) => { | |
if (done) return void controller.close() | |
loaded += value.byteLength | |
onProgress({ loaded, total }) | |
controller.enqueue(value) | |
return read() | |
}) | |
.catch(error => { | |
console.error(error) | |
controller.error(error) | |
}) | |
} | |
} | |
}) | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment