-
Notifications
You must be signed in to change notification settings - Fork 1
/
fetchProgress.js
35 lines (34 loc) · 1.05 KB
/
fetchProgress.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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);
});
}
},
})
);
};
}
fetch(url)
.then(progressHelper(console.log)) // progressHelper used inside the .then()
.then(response => response.blob());