Firebase Cloud功能:错误消息

问题描述 投票:0回答:1

我对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个回答
0
投票

您需要在forEach循环之外移动更新块,同时您还没有正确地返回promise:

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');
    });
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.