Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Javascript中,如何使用fetch()从一个API请求读取多个流块?_Javascript_Node.js_Express_Fetch - Fatal编程技术网

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

在Javascript中,如何使用fetch()从一个API请求读取多个流块?,javascript,node.js,express,fetch,Javascript,Node.js,Express,Fetch,在我的Node/Express后端,我有一个长(10-15秒)的API调用,用于设置用户帐户 通过执行一个简单的fetch('my/api/url')GET请求,从我的前端触发调用 我希望能够向前端/我的用户发送有关请求状态的消息。(“设置个人资料”、“下载联系人”、“处理数据”等) 在我的快速路线中,我正在(尝试)通过以下方式发送数据: exports.setupAccount = async () => { res.write("Getting contacts"); /

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

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

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

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

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!`);
}
我正在努力理解这个时刻,甚至不知道我是否在寻找正确的地方

在我的前端(目前仅限于vanilla 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);
  })
})
fetch(“/my/setup/api”)
。然后(响应=>{
const reader=response.body.getReader();
reader.read().then(异步({done,value})=>{

console.log(“VALUE”,VALUE);//使用
while
循环和
wait
找到了一个适用于vanilla JS的答案:

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()

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