代码之家  ›  专栏  ›  技术社区  ›  Deji James

firebase cloud函数:错误消息

  •  0
  • Deji James  · 技术社区  · 8 年前

    我对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)
    

    这个函数做了我想要它做的事情,但是这个错误消息有点奇怪,不是吗?我做错什么了吗?

    1 回复  |  直到 8 年前
        1
  •  0
  •   Diego P    8 年前

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