-2

Body.json returns a promise.

Is this method asynchronous to avoid blocking on reading large inbound data streams?

Does it do something like setTimeout(sampleStream, 0) repeatedly until the end of the stream is found?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Ben Aston
  • 53,718
  • 65
  • 205
  • 331
  • Btw, `Promise`s perform micro tasks that means, every invocation of their callbacks are appended to the current iteration of the event loop. This can lead to blocking behavior (e.g. if recursion is involved). `setTimeout`'s callback on the other hand is executed within the next iteration of the event loop. –  Jul 19 '16 at 11:21
  • Is micro-task a well defined concept? – Ben Aston Jul 19 '16 at 11:56
  • 1
    Yep [Difference between microtask and macrotask within an event loop context](http://stackoverflow.com/q/25915634/6445533) –  Jul 19 '16 at 12:03

1 Answers1

1

Is .json() asynchronous?

Yes. That's why it returns a promise.

Is this method asynchronous to avoid blocking on reading large inbound data streams?

Yes. You receive the Response right after the headers arrived, and receiving the body might take some time.

Does it do something like setTimeout(sampleStream, 0) repeatedly until the end of the stream is found?

Not exactly. It doesn't use setTimeout, it reads from the stream by repeatably getting promises for the next chunk - just check about reading all bytes from a ReadableStream yourself.
And most importantly, this all happens on a background task without any concerns for JavaScript. As the note on that section tells: Because the reader grants exclusive access, the actual mechanism of how to read cannot be observed. Implementations could use more direct mechanism if convenient.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375