繁体   English   中英

在Javascript中,如何使用fetch()从一个API请求中读取多个流块?

[英]In Javascript, how do I read multiple stream chunks from one API request using fetch()?

在我的Node / Express后端,我有一个很长的(10 - 15秒)API调用来设置用户的帐户。

通过执行简单的fetch('my/api/url') GET请求从我的前端触发调用。

我希望能够向前端/我的用户发送有关请求状态的消息。 (“设置您的个人资料”,“下载您的联系人”,“处理数据”等等)

在我的Express路线中,我(尝试)通过以下方式发送数据:

exports.setupAccount = async () => {
   res.write("Getting contacts");

   // A bunch of code and async awaits
   // and when it's done...
   res.write(`Retrieved ${contacts.length} contacts!`);
}

我正在尝试理解Mozilla Fetch()API ,我甚至不确定我是否正在寻找合适的位置。

在我的前端(现在只是香草JS)我正在做:

fetch('/my/setup/api')
.then(response => {
  const reader = response.body.getReader();
  reader.read().then(async ({ done, value }) => {
    console.log("VALUE", value); // <== This returns a Uint8Array
    var str = String.fromCharCode.apply(null, value);
    console.log("Message from API:", str);
  })
})

res.write() ,但只给我从服务器发送的第一个 res.write() ,并且不会注销后续写入。 如何使用此fetch / getReader()方法读取多个流块?

找到一个与vanilla JS一起使用的答案,使用while循环并await

fetch('/my/api')
.then(async response => {
  const reader = response.body.getReader();

  while(true) {
    const {done, value} = await reader.read();
    // If it's done, there will be no value
    if (done) {
      console.log("Done!");
      break;
    }
    // value is Uint8Array of the chunk bytes
    var str = String.fromCharCode.apply(null, value);
    console.log(str)

  }
})

使用response.text()将读取流完成。 我们也可以使用Response对象来检索其他格式,如blob( response.blob() )或json( response.json() )。

fetch('/my/setup/api')
.then(response => response.text())
.then(text => console.log("Message from API:", text))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM