无法使用JavaScript的ReadableStream将StreamingResponseBody流转换为JSON。

huangapple 未分类评论62阅读模式
英文:

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?

huangapple
  • 本文由 发表于 2020年3月15日 09:46:06
  • 转载请务必保留本文链接:https://java.coder-hub.com/60688986.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定