英文:
Unable to convert StreamingResponseBody streams into JSON using JavaScript's ReadableStream
问题
function getData () {
fetch("MY_URL")
.then(response=>{
const reader = response.body.getReader();
return new ReadableStream({
start(controller) {
return pump();
function pump() {
return reader.read().then(({done, value}) => {
if(done){
controller.close();
console.log("Done");
return;
}
const chunk = new TextDecoder("utf-8").decode(value);
try {
const jsonChunk = JSON.parse(chunk);
console.log(jsonChunk);
controller.enqueue(jsonChunk);
} catch (error) {
console.log("Error parsing JSON:", error);
}
return pump();
});
}
}
});
}).catch(err=>console.log(err));
}
英文:
The back-end API sends streams (of JSON) using Java's StreamingResponseBody. I want to convert the chunks of the streams into proper JSON format using javascript (at front-end). However, it is not working. Here is the code I used:
function getData () {
fetch("MY_URL")
.then(response=>{
const reader = response.body.getReader();
return new ReadableStream({
start(controller) {
return pump();
function pump() {
return reader.read().then({done, value}) => {
if(done){
controller.close();
console.log("Done");
return;
}
const chunk = new TextDecoder("utf-8").decode(value);
console.log(JSON.parse(JSON.stringify(chunk)));
controller.enqueue(value);
return pump();
});
}
}
});
}).catch(err=>console.log(err));
}
How can I fix it so it can convert the chunks into JSON?
专注分享java语言的经验与见解,让所有开发者获益!
评论