使用PDF承诺在Firebase云端函数中使用

我正在使用PDFMake(PDFKit的变体)使用实时数据库触发器在Firebase云端函数上生成PDF。 该函数从数据库获取所有相关数据,然后将其传递给应该生成PDF的函数。

所有这些都是使用Promises完成的。 一切正常,直到PDF实际生成的点。

以下是我的主事件侦听器中的代码:

 exports.handler = (admin, event, storage) => { const quotationData = event.data.val(); // We must return a Promise when performing async tasks inside Functions // Eg: Writing to realtime db const companyId = event.params.companyId; settings.getCompanyProfile(admin, companyId) .then((profile) => { return quotPdfHelper.generatePDF(fonts, profile, quotationData, storage); }) .then(() => { console.log('Generation Successful. Pass for email'); }) .catch((err) => { console.log(`Error: ${err}`); }); }; 

要生成PDF,这是我的代码:

 exports.generatePDF = (fonts, companyInfo, quotationData, storage) => { const printer = new PdfPrinter(fonts); const docDefinition = { content: [ { text: [ { text: `${companyInfo.title}\n`, style: 'companyHeader', }, `${companyInfo.addr_line1}, ${companyInfo.addr_line2}\n`, `${companyInfo.city} (${companyInfo.state}) - INDIA\n`, `Email: ${companyInfo.email} • Web: ${companyInfo.website}\n`, `Phone: ${companyInfo.phone}\n`, `GSTIN: ${companyInfo.gst_registration_number} • PAN: AARFK6552G\n`, ], style: 'body', //absolutePosition: {x: 20, y: 45} }, ], styles: { companyHeader: { fontSize: 18, bold: true, }, body: { fontSize: 10, }, }, pageMargins: 20, }; return new Promise((resolve, reject) => { // const bucket = storage.bucket(`${PROJECT_ID}.appspot.com`); // const filename = `${Date.now()}-quotation.pdf`; // const file = bucket.file(filename); // const stream = file.createWriteStream({ resumable: false }); const pdfDoc = printer.createPdfKitDocument(docDefinition); // pdfDoc.pipe(stream); const chunks = []; let result = null; pdfDoc.on('data', (chunk) => { chunks.push(chunk); }); pdfDoc.on('error', (err) => { reject(err); }); pdfDoc.on('end', () => { result = Buffer.concat(chunks); resolve(result); }); pdfDoc.end(); }); }; 

这里有什么可能是错误的是阻止了承诺,从而导致代码按预期执行?

在firebase日志上,我所看到的是Function execution took 3288 ms, finished with status: 'ok'

基于执行时间和缺less错误,它看起来像你正在成功创buildPDF的缓冲区,但你实际上并没有从函数返回它。

 .then((profile) => { return quotPdfHelper.generatePDF(fonts, profile, quotationData, storage); }) .then(() => { console.log('Generation Successful. Pass for email'); }) 

在上面的代码中,您将结果传递给下一个块,但是返回该块的未定义。 这个Promise链的最终结果是未定义的。 要传递结果,您需要在Promise链的末尾返回它:

 .then((profile) => { return quotPdfHelper.generatePDF(fonts, profile, quotationData, storage); }) .then(buffer => { console.log('Generation Successful. Pass for email'); return buffer; })