Skip to content

Instantly share code, notes, and snippets.

@korzio
Created April 4, 2019 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save korzio/9aa3d7519fea9db1eed59938578b6170 to your computer and use it in GitHub Desktop.
Save korzio/9aa3d7519fea9db1eed59938578b6170 to your computer and use it in GitHub Desktop.
function getResponseSize(url) {
return fetch(url).then(response => {
const reader = response.body.getReader()
let total = 0
return reader.read().then(function processResult(result) {
if (result.done) return total
const value = result.value
total += value.length
console.log('Received chunk', value)
return reader.read().then(processResult)
})
})
}
@korzio
Copy link
Author

korzio commented Apr 4, 2019

async function getResponseSize(url) {
  const response = await fetch(url)
  const reader = response.body.getReader()
  let total = 0
  let result = { value: '', done: false }
  
  do {
    result = await reader.read()
    
    const value = result.value
    total += value.length
    console.log('Received chunk', value)
  } while (!result.done)

  return total
}

@korzio
Copy link
Author

korzio commented Oct 3, 2019

async function getResponseSizeAsync(url) {
  const response = await fetch(url)
  const reader = response.body.getReader()
  let total = 0
  
  while (true) {
    const result = await reader.read()
    if (result.done) {
      return total
    }

    const value = result.value
    total += value.length
    console.log('Received chunk', value)
  }
}

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