Skip to content

Instantly share code, notes, and snippets.

@jamesplease
Last active April 4, 2018 16:48
Show Gist options
  • Save jamesplease/916c2d70b468220c8ecfdf3251e0df25 to your computer and use it in GitHub Desktop.
Save jamesplease/916c2d70b468220c8ecfdf3251e0df25 to your computer and use it in GitHub Desktop.
// res.bodyUsed is true immediately after the method is called. That is awesome!
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(res => {
console.log('Immediately when the res is received:', res.bodyUsed);
const body = res.json()
.then(stuff => {
console.log('Ok response from res.json', stuff);
console.log('Body read as JSON', res.bodyUsed);
});
console.log('Immediately after trying to read the body', res.bodyUsed);
});
// res.bodyUsed is true after the first chunk is read
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(res => {
console.log('Immediately when the res is received:', res.bodyUsed);
const reader = res.body.getReader();
console.log('After reader acquired', res.bodyUsed);
const onReadChunk = chunk => {
if (chunk.done) {
console.log('Streaming is complete', res.bodyUsed);
}
if (!chunk.done) {
reader.read().then(onReadChunk)
}
}
console.log('Just before the first read', res.bodyUsed);
// Do the first read().
reader.read().then(chunk => {
console.log('Just after first chunk is read', res.bodyUsed);
onReadChunk(chunk);
});
console.log('Immediately after reader.read is called', res.bodyUsed);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment