Re: [whatwg/fetch] idea: Accept a iterator as a body (#809)

> Would a constructor that takes an iterator and returns a ReadableStream of
those values fix this problem?

I guess... 
There is already one node specific module ([stream-from-iterator](https://github.com/schnittstabil/stream-from-iterator/blob/master/index.js))

I guess it could be useful to have a iterator to ReadableStream constructor converter for other purposes too, but then i would wish for this to be included in the steps of creating a body in the Request/Response constructor

> if body is a iterable let body be the result of converting a iterator to ReadableStream using the x constructor

------

But then I think we are digging a little bit into this issue also: https://github.com/w3c/FileAPI/issues/40 
@annevk said something about using `Symbol` to have have something any IDL convertible to streams

> I think the main benefit of a protocol (similar to Symbol.iterator) is that a) userland objects can participate, b) we can potentially make it easier to add such functionality to future IDL classes, and c) we settle any future naming disputes.

so if all iterators had `Symbol.toStream` you could perhaps do something like this:


```js
// make up some symbol name
Symbol.toStream = Symbol('toStream')

// polyfill all iterators to have `Symbol.toStream`
Object.getPrototypeOf(generator())[Symbol.toStream] = function(){
  // dirty hack to convert iterator to ReadableStream
  return new Response([...this].join('')).body
}

// sample iterator
function* generator() {
  yield 'abc'
  yield 'def'
}

var iterator = generator()
var stream = iterator[Symbol.toStream]()
new Response(stream).text().then(console.log)

// or just simply iterator when the fetch spec understands Symbol.toStream
new Response(iterator).text().then(console.log)
```

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/fetch/issues/809#issuecomment-421407687

Received on Friday, 14 September 2018 16:11:37 UTC