【问题标题】:Sending HTTP answer without waiting for my queries to complete - Cloud Functions - Firebase无需等待我的查询完成即可发送 HTTP 答案 - Cloud Functions - Firebase
【发布时间】:2018-06-25 19:34:00
【问题描述】:

我编写了一个由链接触发的云功能,但我遇到了问题。答案是在所有指令完成之前发送的,我尝试使用 Promise 但没有成功。

我的代码:

    exports.controlaPtsMensal = functions.https.onRequest((req, res) => {
    var dia_atual = new Date();
    var usuariosRef = admin.database().ref('users');
    usuariosRef.on('value', function(snapshot){
        if(snapshot.exists()){
            var user = snapshot.val();
            var cont = 0;
            for(var i in user){
                cont = cont + 1;
                var data_pontos = user[i].data_controle_pts;
                var data = new Date(data_pontos);
                var timeDiff = Math.abs(dia_atual.getTime() - data.getTime());
                var diferenca = Math.ceil(timeDiff / (1000 * 3600 * 24)) - 1;
                admin.auth().getUser(i)
                  .then(function(userRecord) {
                    console.log("Email do usuário: ",userRecord.email);
                    if(userRecord.email == "test@hotmail.com"){//diferenca == 30 && 
                        send({
                            //to: [userRecord.email],
                            to: [test@gmail.com'],
                            subject: 'Último dia para usar seus pontos!',
                            html: '<b>Mensagem de App Anjo ' + '<br></b><br><br><b>Mensagem: </b><br>Hoje é o último dia para você'
                            + ' resgatar ou doar seus pontos, vamos lá ! :)'
                        });
                    }
                  })    
            }
          res.status(200).send('Função de controle de pontos executada com sucesso!');
        }
    });
});

提前谢谢你。

【问题讨论】:

    标签: node.js firebase firebase-realtime-database promise google-cloud-functions


    【解决方案1】:

    您必须将所有对 admin.auth().getUser(i).then(...) 的调用中的所有承诺收集到一个数组中,然后将该数组传递给 Promise.all() 以便等待所有工作完成之前 发送最终响应。

    这是一种非常常见的模式,应该很容易找到与您正在做的事情相似的示例。例如,this sample

    【讨论】:

    • 非常感谢。我做到了,我的问题解决了!
    猜你喜欢
    • 2012-11-18
    • 2016-07-28
    • 1970-01-01
    • 2022-08-17
    • 1970-01-01
    • 2018-08-13
    • 2018-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多