简体   繁体   English

发送流作为 axios 请求的响应

[英]Sending streams as response of a axios request

I am making a request with an .xlsx file to the server, the server is generating a PDF with puppeteer, and I want to send the stream back to the client in an array to download them, but the response is not awaiting them and in the front I get an empty array.我正在向服务器发出一个带有.xlsx文件的请求,服务器正在使用 puppeteer 生成一个 PDF,我想将流以数组的形式发送回客户端以下载它们,但响应并未等待它们,并且在前面我得到一个空数组。

Node.js/Reactjs Node.js/Reactjs

router.post('/generate-payslip', async (req, res) => {
  const data = JSON.parse(req.body)
  let responsePDF = []

  data.map(async data => {
    responsePDF.push(await generatePayslipPDF(data))
    const payslips = await Payslip.findOne({ date: data.Date, name: data.Name })
    if (payslips) {
    } else {
      let payslip = new Payslip({
        date: data.Date,
        name: data.Name,
        data: data
      })
      payslip = await payslip.save()
    }

  })

  res.send(responsePDF)
})

You need to wait for the mapping of data to finish.您需要等待data映射完成。

Your call to data.map returns a new array of promises that you can wait for using Promise.all .您对data.map调用会返回一个新的data.map数组,您可以使用Promise.all等待Promise.all

const promises = data.map(async data => {
  // ...
})

// wait for all the promises to resolve
await Promise.all(promises)

res.send(responsePDF)

Note, however, that this runs the map in "parallel".但是请注意,这会以“并行”方式运行地图。 There is no guarantee that the PDFs are pushed to the responsePDF array in order.无法保证 PDF 按顺序推送到responsePDF数组。

To guarantee the order, you can return the generated PDF in the map function:为了保证顺序,可以在map函数中返回生成的PDF:

const responsePDF = await Promise.all(data.map(async data => {
  // ...
  return await generatePayslipPDF(data)
}))

res.send(responsePDF)

Alternatively you can use a for...of loop to run it serially (one at a time).或者,您可以使用 for...of 循环连续运行它(一次一个)。 That way you do not need to use Promise.all .这样你就不需要使用Promise.all

for (const payslip of data) {
  responsePDF.push(await generatePayslipPDF(payslip))
  // ...
}


res.send(responsePDF)

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

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