【问题标题】:Firebase Cloud Function: error messageFirebase 云功能:错误消息
【发布时间】:2018-07-19 12:36:31
【问题描述】:

我对 Node.js 和 Firebase 云功能相当陌生。我在下面转载了我的云功能示例:

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

问题是我在 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)

该函数完全按照我的意愿执行,但该错误消息有点奇怪,不是吗?是不是我做错了什么?

【问题讨论】:

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


    【解决方案1】:

    您需要将更新块移到 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');
        });
      });
    });
    

    【讨论】:

    • 感谢您的回复。问题是我的目标是对每个用户节点进行更新。这就是为什么我把它留在循环中。有没有解决的办法?对不起,如果这是一个愚蠢的问题。
    猜你喜欢
    • 2018-11-17
    • 1970-01-01
    • 1970-01-01
    • 2019-01-13
    • 2018-11-25
    • 2016-11-02
    • 2019-11-21
    • 2021-11-20
    • 2021-12-01
    相关资源
    最近更新 更多