Context
In my current understanding, the ReadableStream
constructor allows you to chop big pieces of data into smaller pieces (chunks) that you can then read.
In the case of fetch
you already get the ReadableStream ready to consume, i.e the data is already in chunks, and can be found at the response’s body
. But we may also want to produce a stream (for others to consume.)
A use case of this would any very large file uploaded by the user, that has to be processed by pieces.
So the doubt is what is the difference between start
running sync or async code, as I show below.
Basic syntax and example (uses var
to easy copy/paste in the console):
var u8View = new Uint8Array(30); //typed array with 30 zeros.
var stream = new ReadableStream({
start(controller) {
// to an approx. this will create an "array of chunks" from u8View that a user can access later
controller.enqueue(u8View)
controller.close()
}
})
stream.getReader().read().then(d => console.log(d))
var stream1 = new ReadableStream({
start(controller) {
setTimeout(() => {
controller.enqueue(u8View)
controller.close()
}, 1000)
}
})
stream1.getReader().read().then(d => console.log(d))
You will notice that the code basically does the same.
I believe this is because read
only passes the value once it is fulfilled (resolved or rejected). I take this from a comment in the MDN’s example.
- Is this correct?
- Why does it seem weird to me, is this just a common/expected behaviour?
- So as long as you make sure to
enqueue
something, it doesn’t really matter how you handle the code (even if looping through the chunks)?