Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mzgoddard/2dd196bf67145565cb317beeb14502d0 to your computer and use it in GitHub Desktop.
Save mzgoddard/2dd196bf67145565cb317beeb14502d0 to your computer and use it in GitHub Desktop.
Example manual implementation of fetch().then(response => response.arrayBuffer())
// Body mixin arrayBuffer helper.
return response.arrayBuffer();
// Example implementation of arrayBuffer().
const reader = response.body.getReader();
return new Promise((resolve, reject) => {
const chunks = [];
const step = function () {
reader.read().then(({done, value}) => {
if (done) {
const uint8 = new Uint8Array(chunks.reduce((carry, chunk) => carry + chunk.length, 0));
let position = 0;
for (let i = 0; i < chunks.length; i++) {
uint8.set(chunks[i], position);
position += chunks[i].length;
}
resolve(uint8.buffer);
} else {
chunks.push(value);
setTimeout(step);
}
}, reject);
};
setTimeout(step);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment