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

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

Unable to convert StreamingResponseBody streams into JSON using JavaScript's ReadableStream

问题

  1. function getData () {
  2. fetch("MY_URL")
  3. .then(response=>{
  4. const reader = response.body.getReader();
  5. return new ReadableStream({
  6. start(controller) {
  7. return pump();
  8. function pump() {
  9. return reader.read().then(({done, value}) => {
  10. if(done){
  11. controller.close();
  12. console.log("Done");
  13. return;
  14. }
  15. const chunk = new TextDecoder("utf-8").decode(value);
  16. try {
  17. const jsonChunk = JSON.parse(chunk);
  18. console.log(jsonChunk);
  19. controller.enqueue(jsonChunk);
  20. } catch (error) {
  21. console.log("Error parsing JSON:", error);
  22. }
  23. return pump();
  24. });
  25. }
  26. }
  27. });
  28. }).catch(err=>console.log(err));
  29. }
英文:

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:

  1. function getData () {
  2. fetch("MY_URL")
  3. .then(response=>{
  4. const reader = response.body.getReader();
  5. return new ReadableStream({
  6. start(controller) {
  7. return pump();
  8. function pump() {
  9. return reader.read().then({done, value}) => {
  10. if(done){
  11. controller.close();
  12. console.log("Done");
  13. return;
  14. }
  15. const chunk = new TextDecoder("utf-8").decode(value);
  16. console.log(JSON.parse(JSON.stringify(chunk)));
  17. controller.enqueue(value);
  18. return pump();
  19. });
  20. }
  21. }
  22. });
  23. }).catch(err=>console.log(err));
  24. }

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:

确定