简体   繁体   English

我有一个贯穿数组的 API,我想在每个数组元素上向客户端发送数据

[英]I have an API that runs through an array and I want to send data to the client on each array element

I have an API that runs through an array and I want so send data to the client on each array element, i have tried using res.write with res.flush but it still waits until the end to send everything, is there a way that the data can be sent by chunks?我有一个 API 贯穿一个数组,我想在每个数组元素上向客户端发送数据,我尝试使用 res.write 和 res.flush 但它仍然等到最后发送所有内容,有没有办法数据可以分块发送吗?

for (let i = 0; i < searchUrl.length; i++) {
      const element = searchUrl[i];
      const element_details = await getDetailsforURL(element)
      res.write(JSON.stringify(element_details))
      res.flush()
      //return_array.push(element_details)
    }
    res.end()

.write() adds content to the body of the response. .write()将内容添加到响应的正文中。 Basically with every res.write() you add data to the body and send it with res.end() .基本上每次res.write()都会将数据添加到正文并使用res.end()发送。 If you want to send it in chunks you need one request per chunk, meaning that the client needs to continuously send requests until all data is received.如果要分块发送,则每个块需要一个请求,这意味着客户端需要不断发送请求,直到收到所有数据。

If you don't want to send the whole array, you could do the processing on the server side and send the result to the client:如果您不想发送整个数组,您可以在服务器端进行处理并将结果发送给客户端:

let response = [];
for (let i = 0; i < searchUrl.length; i++)
    const element = searchUrl[i];
    const element_details = await getDetailsforURL(element);
    response.push(element_details);
    
}
res.write(JSON.stringify(element_details));
res.end();

暂无
暂无

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

相关问题 对于数组中的每个元素,我希望它有另一个元素,每个元素都有独特的动作 - For each element inside an array I want it to have another for each that will have unique action 我有一个JavaScript数组,我想下载数组中的每个图像 - I have a JavaScript array and I want to download each image in the array 我想从数组中读取每个元素以及该元素的深度位置 - I want to read each element and depth position of that element from an array 我有一组不同的 ID,我想从每个 ID 中获取数据。 可能吗? - I have an array of different IDs and I want to fetch data from each IDs . Is it possible? 在 Javascript 中,循环对象数组时,如何将每个元素的名称发送到控制台? - In Javascript, when looping through an array of objects, how do I send each element's name to the console? 如何通过ajax发送以下数组中的每个元素? - How do I send through ajax each element from the following array? 有一个带有 colors 的数组,我想通过 setInterval 无限旋转 - have an array with colors that I want to rotate infinitely through setInterval 我想给我每个数组元素一个数字 - I want to give each of my array element a number 我有一个包含 2 个 object 的数组,在每个 object 中我有一个 object 数组。 我只想获取与属性匹配的那些数据 - I have an array which has 2 object, In each object i have a array of object. I want to get only those data's which matches the attributes 我有一个对象数组和一个对象,我想遍历对象,同时将对象值与数组中的值匹配 - I have an array of objects and an object I want to loop through an object while matching object values with the values in the array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM