Created
July 16, 2019 16:33
-
-
Save mzgoddard/2dd196bf67145565cb317beeb14502d0 to your computer and use it in GitHub Desktop.
Example manual implementation of fetch().then(response => response.arrayBuffer())
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
// 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