node.js - 在 Firebase Cloud Functions 上使用 PDFMake 的 promise

标签 node.js firebase promise pdfkit pdfmake

我正在使用 PDFMake(PDFKit 的变体)通过实时数据库触发器在 Firebase Cloud Functions 上生成 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();
  });
};

这里可能有什么问题阻止了 promise,从而阻止了引用代码按预期执行?

在 firebase 日志上,我只看到函数执行耗时 3288 毫秒,完成状态:'ok'

最佳答案

根据执行时间和没有出现错误,您似乎成功地为 PDF 创建了缓冲区,但实际上并没有从函数中返回它。

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

在上面的代码中,您将结果传递给下一个 then block ,但随后从该 block 返回 undefined 。这个 Promise 链的最终结果将是不确定的。要传递结果,您需要在 Promise 链的末尾返回它:

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

关于node.js - 在 Firebase Cloud Functions 上使用 PDFMake 的 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47143187/

相关文章:

javascript - Mongodb 并行运行数千个查询

node.js - Meteor - collection.find() 总是返回所有字段

node.js - 如何按数组搜索

javascript - 拉动用户组的最快方法(数百万行)

javascript - 使用 Promise 链接 http 请求

node.js - 在 Q 中记录所有拒绝的 promise

Javascript 比较 bool 值

swift - 快速检索子键并显示在标签中

javascript - 就 Firebase 的每日配额而言, "read"到底是什么构成的?

javascript - Expressjs MVC 在路由器中无法让 listAll() 从 mongoose 返回数据