Skip to content

Instantly share code, notes, and snippets.

@sabesansathananthan
Created February 9, 2021 08:09
Show Gist options
  • Save sabesansathananthan/3f81bf1c79b1311f8e9784bc7a4ec921 to your computer and use it in GitHub Desktop.
Save sabesansathananthan/3f81bf1c79b1311f8e9784bc7a4ec921 to your computer and use it in GitHub Desktop.
Axios Vs Fetch
// original code: https://github.com/AnthumChris/fetch-progress-indicators
const element = document.getElementById('progress');
fetch('url')
.then(response => {
if (!response.ok) {
throw Error(response.status+' '+response.statusText)
}
// ensure ReadableStream is supported
if (!response.body) {
throw Error('ReadableStream not yet supported in this browser.')
}
// store the size of the entity-body, in bytes
const contentLength = response.headers.get('content-length');
// ensure contentLength is available
if (!contentLength) {
throw Error('Content-Length response header unavailable');
}
// parse the integer into a base-10 number
const total = parseInt(contentLength, 10);
let loaded = 0;
return new Response(
// create and return a readable stream
new ReadableStream({
start(controller) {
const reader = response.body.getReader();
read();
function read() {
reader.read().then(({done, value}) => {
if (done) {
controller.close();
return;
}
loaded += value.byteLength;
progress({loaded, total})
controller.enqueue(value);
read();
}).catch(error => {
console.error(error);
controller.error(error)
})
}
}
})
);
})
.then(response =>
// construct a blob from the data
response.blob()
)
.then(data => {
// insert the downloaded image into the page
document.getElementById('img').src = URL.createObjectURL(data);
})
.catch(error => {
console.error(error);
})
function progress({loaded, total}) {
element.innerHTML = Math.round(loaded/total*100)+'%';
}
@oneberto
Copy link

oneberto commented Mar 1, 2021

thanks man

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment