如firebase docs中所述,需要
“通過回傳 JavaScript 承諾來決議執行異步處理的函式(也稱為“后臺函式”)。” (
我應該怎么做才能正確終止該功能?
// adapting the demo code by Volodymyr Golosay published on https://medium.com/firebase-developers/how-to-generate-and-store-a-pdf-with-firebase-7faebb74ccbf // library installed -> npm install pdfmake const functions = require("firebase-functions"); const admin = require("firebase-admin"); admin.initializeApp(); const db = admin.firestore(); const Printer = require('pdfmake'); const fonts = require('pdfmake/build/vfs_fonts.js'); const fontDescriptors = { Roboto: { normal: Buffer.from(fonts.pdfMake.vfs['Roboto-Regular.ttf'], 'base64'), bold: Buffer.from(fonts.pdfMake.vfs['Roboto-Medium.ttf'], 'base64'), italics: Buffer.from(fonts.pdfMake.vfs['Roboto-Italic.ttf'], 'base64'), bolditalics: Buffer.from(fonts.pdfMake.vfs['Roboto-Italic.ttf'], 'base64'), } }; exports.generateDemoPdf = functions // trigger by 'document.onCreate', while demo uses 'https.onRequest' .firestore .document('collection/{docId}') .onCreate(async (snap, context) => { const printer = new Printer(fontDescriptors); const chunks = []; // define the content of the pdf-file const docDefinition = { content: [{ text: 'PDF text is here.', fontSize: 19 } ] }; const pdfDoc = printer.createPdfKitDocument(docDefinition); pdfDoc.on('data', (chunk) => { chunks.push(chunk); }); pdfDoc.on('end', async () => { const result = Buffer.concat(chunks); // Upload generated file to the Cloud Storage const docId = "123456789" const bucket = admin.storage().bucket(); const fileRef = bucket.file(`${docId}.pdf`, { metadata: { contentType: 'application/pdf' } }); await fileRef.save(result); console.log('result is saved'); // NEEDS PROPER TERMINATION HERE?? NEEDS TO RETURN A PROMISE?? FIREBASE DOCS: https://firebase.google.com/docs/functions/terminate-functions?hl=en // the demo with 'https.onRequest' uses the following line to terminate the function properly: // response.send(result); }); pdfDoc.on('error', (err) => { return functions.logger.log('An error occured!'); }); pdfDoc.end(); });uj5u.com熱心網友回復:
我認為您的代碼中的一切都很好。渲染檔案并將其保存到存盤似乎需要 1m 34s。
完成所有微觀和宏觀任務后,云功能將自動終止。就在你最后一次等待之后。
要檢查需要多長時間以及保存后是否立即終止,您可以在本地計算機上運行firebase 模擬器。
您將在終端中看到日志并同時觀看存盤。
uj5u.com熱心網友回復:
我懷疑你確實終止了——這就是承諾的本質。您的函式以 200 狀態“終止”,回傳 PDF 保存結果的 PROMISE。當 PDF 保存稍后實際終止時,將記錄結果并解決承諾。這種行為是你回傳承諾的原因。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/415991.html
標籤:
下一篇:單擊按鈕時更改按鈕名稱

