I am using PDFKit for generating invoice PDFs, just came up with an issue, where my function is returning undefined, but PDF is getting generated (maybe a bit late). I want my function to only return once all work Is done, from generating PDF to completing the file.
My function is like this:
exports.generatePdf = async (invoiceId) => {
try {
let invoicePath = `uploads/invoices/filename.pdf`
// Create doc
let doc = new PDFDocument({ size: "A4", margin: 30 })
const stream = fs.createWriteStream(invoicePath)
doc.pipe(stream)
// All doc styling goes here
// End
doc.end()
stream.on('finish', function () {
return invoicePath
})
} catch (err) {
console.error(err)
throw err
}
}
I want my function (generatePdf) to return invoicePath after everything is completed.