【问题标题】:How to work with promise with firestore + pdfmake in Firebase Functions如何在 Firebase 函数中与 firestore + pdfmake 一起使用 Promise
【发布时间】:2018-05-31 23:45:17
【问题描述】:

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

  • 收藏
    • 文档
      • 字段1
      • 字段 2
      • 另一个系列
        • 文档
          • 字段 2 ...
        • 文档 2 ...
    • 文档 2 ...

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

错误是我的“第二个然后”在第一个“那么”之前返回,所以我的 PDF 文件在屏幕上呈现一个空白文件。 它没有显示任何错误,但在控制台上我可以看到在返回响应后获取了数据。在发送任何响应之前,我需要先解决然后包含在循环中的第一个问题,但它不会发生

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)
}

})

【问题讨论】:

  • 错误是什么?请明确点。此外,您没有显示函数的完整代码 - 它缺少函数定义。
  • @DougStevenson 我更新了描述。错误是我的“第二个然后”在第一个“然后”被解决之前返回,所以我的 PDF 文件在屏幕上呈现一个空白文件。它没有显示任何错误,但在控制台上我可以看到在返回响应后获取了数据。
  • 你能提供剩下的代码吗?
  • 你肯定没有在整个函数中正确使用 Promise。

标签: node.js firebase google-cloud-firestore google-cloud-functions pdfmake


【解决方案1】:

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

我做了另一个函数,什么返回我想要的 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});
    })
})

【讨论】:

    猜你喜欢
    • 2021-06-24
    • 1970-01-01
    • 2018-04-18
    • 2022-11-13
    • 2021-10-11
    • 2019-10-24
    • 1970-01-01
    • 2020-08-24
    • 1970-01-01
    相关资源
    最近更新 更多