如何在 Firebase 函数中使用 promise 和 firestore + pdfmake

How to work with promise with firestore + pdfmake in Firebase Functions

我正在尝试制作一个 pdf 文件,使用 firebase 函数从 firestore 获取数据,但现在我遇到了问题。 我有这个数据结构:

我需要将此结构转换为 json 以在 pdfMake 上显示。我知道我必须使用承诺,但最后的 object 并没有像我预期的那样出现。当我使用第一层(仅来自 de firsts 文档的字段)时,工作正常,但是当我尝试输入这些相同的文档 Collection 时,我收到错误消息。我会把代码放在下面。

错误是我的 'second then' return 比第一个 "then" 得到解决,所以我的 PDF 文件在屏幕上呈现空白文件。 它没有显示任何错误,但在控制台上我可以看到在响应 returned 后获取数据。在发送任何响应之前,我需要解决第一个然后包含在循环中的问题,但它没有发生

exports.helloPDF = functions.https.onRequest( (request, response) => {
try {
    db.collection('lista_substituicao').get().then((lista_substituicao) =>{
        let docDefinition = { //definitions will be used on pdf file
            background: function () {
                return [
                    {
                    image: 'bg.jpg',
                    width: 550
                }
            ];
        },
        content: []
    };

    lista_substituicao.forEach( grupo => {
        let grupoDef = {id: grupo.id, ...grupo.data()}
        let tabelaGrupo = {
            table: {
                widths: ['*'],
                body: [
                    [`Grupo ${grupoDef.grupo}`]
                ]
            }
        } 

        db.collection(`lista_substituicao/${grupoDef.id}/alimentos/`).get().then(alimentos =>{
            let alimentosTable = {
                table: {
                    widths: ['*'],
                    body: [
                        ["Alimento"]
                    ]
                }
            }
            alimentos.forEach(alimentoDef =>{
                let alimento = {id: alimentoDef.id, ...alimentoDef.data()}
                alimentosTable['table']['body'].push([alimento.alimento])                    
            })

            tabelaGrupo['table']['body'].push(alimentosTable)
            docDefinition['content'].push(tabelaGrupo)
        })
    })

    return docDefinition

}).then((finalDocDefinition) =>{
    console.log(finalDocDefinition) // i get undefined here
    let doc = printer.createPdfKitDocument(docDefinition);
                response.setHeader('Content-Type', 'application/pdf');
                doc.end();
                return doc.pipe(response)
})


 } catch (error) {
    console.log(error)
}

})

我更改了代码,现在它按预期工作了。

我根据需要做了另一个函数,什么是 return 一棵 json 树。 代码:

 db.collection(`lista_substituicao`).get().then(lista_substituicao =>{
    let grupos = []
    let grupoPromisses = []

    lista_substituicao.forEach(grupo => {
        let grupoData = {id: grupo.id, ...grupo.data(), alimentos: []}
        let promise = db.collection(`lista_substituicao/${grupo.id}/alimentos/`).get()
        grupoPromisses.push(promise)
        grupos[grupo.id] = grupoData
    })

    Promise.all(grupoPromisses).then(alimentos => {
        alimentos.forEach(alimentos =>{
            alimentos.forEach(alimento =>{
                let idGrupo = alimento.ref.parent.parent.id
                grupos[idGrupo]['alimentos'].push(alimento.data())
            })
        })
        return response.status(201).json({...grupos});
    })
})