简体   繁体   English

Firebase Cloud功能:错误消息

[英]Firebase Cloud Function: error message

I am fairly new to Node.js and Firebase cloud functions. 我对Node.js和Firebase云功能还很陌生。 I have reproduced below, a sample of my cloud function: 我在下面转载了我的云函数示例:

exports.sync = functions.https.onRequest((req, res) => {
  admin.database().ref('users').once('value').then(function(snapshot) {
    var updates = {};

    admin.database().ref("Player").child("playerweek12").once('value')
      .then(function(dataSnapshot) {
        var orderedPlayers = dataSnapshot.val();

        snapshot.forEach(function(userSnapshot) {
          var users = userSnapshot.val();
          var selection = users.selection;
          updates[`/users/${userSnapshot.key}/week1`] = 10;
          updates[`/users/${userSnapshot.key}/week2`] = 10;

          admin.database().ref().update(updates).then(function() {
            res.send('it worked');
          });
        });
      });
  });
});

The issue is that I keep getting the following error message in my Firebase function log: 问题是我在Firebase功能日志中不断收到以下错误消息:

Error: Can't set headers after they are sent. 
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11) 
    at ServerResponse.header (/var/tmp/worker/node_modules/express/lib/response.js:767:10) 
    at ServerResponse.send (/var/tmp/worker/node_modules/express/lib/response.js:170:12) 
    at /user_code/index.js:33:16 
    at process._tickDomainCallback (internal/process/next_tick.js:135:7)

The function did exactly what I wanted it to, but that error message is kind of weird is it not? 该函数确实完成了我想要的功能,但是该错误消息有点奇怪,不是吗? Is there something that I am doing wrong? 我做错了什么吗?

You need to move the update block outside the forEach loop also you are not returning promises correctly: 您需要将更新块移到forEach循环之外,而且您没有正确返回诺言:

exports.sync = functions.https.onRequest((req, res) => {
  return Promise.all([admin.database().ref('users').once('value'), admin.database().ref("Player").child("playerweek12").once('value')]).then(results => {
    const users = results[0];
    const player = results[1];
    const updates = {};
    users.forEach(function (userSnapshot) {
      var users = userSnapshot.val();
      var selection = userSnapshot.val().selection;
      updates[`/users/${userSnapshot.key}/week1`] = 10;
      updates[`/users/${userSnapshot.key}/week2`] = 10;
    });
    return admin.database().ref().update(updates).then(function () {
      return res.send('it worked');
    });
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM