Created
February 9, 2021 08:09
-
-
Save sabesansathananthan/3f81bf1c79b1311f8e9784bc7a4ec921 to your computer and use it in GitHub Desktop.
Axios Vs Fetch
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
// 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)+'%'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks man