Skip to content

Instantly share code, notes, and snippets.

@atomize
Created August 19, 2019 01:59
Show Gist options
  • Save atomize/50d5e5f50ae33341a26068dfeb465e24 to your computer and use it in GitHub Desktop.
Save atomize/50d5e5f50ae33341a26068dfeb465e24 to your computer and use it in GitHub Desktop.
get progress of fetch()
async function newguy(){
let response = await fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits?per_page=100');
const reader = response.body.getReader();
// Step 2: get total length
const contentLength = +response.headers.get('Content-Length');
// Step 3: read the data
let receivedLength = 0; // received that many bytes at the moment
let chunks = []; // array of received binary chunks (comprises the body)
while(true) {
const {done, value} = await reader.read();
if (done) {
break;
}
chunks.push(value);
receivedLength += value.length;
console.log(`Received ${receivedLength} of ${contentLength}`)
}
// Step 4: concatenate chunks into single Uint8Array
let chunksAll = new Uint8Array(receivedLength); // (4.1)
let position = 0;
for(let chunk of chunks) {
chunksAll.set(chunk, position); // (4.2)
position += chunk.length;
}
// Step 5: decode into a string
let result = new TextDecoder("utf-8").decode(chunksAll);
// We're done!
let commits = JSON.parse(result);
return commits
}
newguy().then(commits=>alert(commits[0].author.login))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment