简体   繁体   中英

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.

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.

Your call to data.map returns a new array of promises that you can wait for using 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.

To guarantee the order, you can return the generated PDF in the map function:

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). That way you do not need to use Promise.all .

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


res.send(responsePDF)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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