Fetch with Streams
Apr. 2015
Requirements
Fetch API (as of Chrome 42)
fetch(‘https://example.com/’).then(function(res) {
return res.text();
}).then(function(text) {
// We have the body string here!
console.log(text);
});
var promise = res.text();
promise は、ダウンロードが終わらないと fulfill されない
XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open(‘https://example.com/’);
xhr.onprogress = function() {
var responseSoFar = xhr.responseText;
...
};
xhr.send();
XMLHttpRequest には、progress event が配信される
テキストを受け取っている時のみ、途中のレスポンスボディが見られる
Fetch API vs. XHR
| Fetch API | XHR text | XHR binary |
progress event | NG | OK | OK |
partial result | NG | OK ただし、すでに読んだ結果を忘れられない | NG |
Fetch API vs. XHR
| Fetch API | XHR text | XHR binary | Fetch API + Streams |
progress event | NG | OK | OK | OK |
partial result | NG | OK ただし、すでに読んだ結果を忘れられない | NG | OK |
Streams API https://streams.spec.whatwg.org/
producer
consumer
data (text, arraybuffer, object, …)
Streams API https://streams.spec.whatwg.org/
producer
data
ReadableStream
consumer
data
WritableStream
Streams API https://streams.spec.whatwg.org/
producer
consumer
rs.pipeTo(ws)
ReadableStream
interface ReadableStream {
void cancel(optional any reason);
ReadableStreamReader getReader();
}
ReadableStreamReader
interface ReadableStreamReader {
void cancel(optional any reason);
readonly attribute Promise<undefined> closed;
Promise<any> read();
void releaseLock();
}
ReadableStreamReader.read
var promise = reader.read().then(function(r) {
if (r.done) {
// done!
} else {
var data = r.value;
}
});
Example: consume
function consume(reader) {
var chunks = [];
function rec() {
return reader.read().then(function(r) {
if (r.done) { return chunks; }
else {
chunks.push(r.value);
return rec();
}
});
}
return rec();
}
WritableStream
TBD
Response.body https://github.com/yutakahirano/fetch-with-streams
interface Response {
...
readonly attribute ReadableByteStream body;
}
fetch(‘https://example.com/’).then(function(res) {
return consume(res.body.getReader());
}).then(function(chunks) {...});
TODO