Javascript 如何在then语句中定义firebase cloud函数触发器

Javascript 如何在then语句中定义firebase cloud函数触发器,javascript,firebase,google-cloud-functions,Javascript,Firebase,Google Cloud Functions,我需要确保在定义firebase函数之前运行此代码,因为它取决于代码中设置的变量: const hotelBedTimeouts = []; var beds = db.ref('/beds'); // Initialise the bed timeout holder object beds.once("value", function(snapshot){ var hotels = snapshot.val(); for (var i = 0; i < hotels.le

我需要确保在定义firebase函数之前运行此代码,因为它取决于代码中设置的变量:

const hotelBedTimeouts = [];

var beds = db.ref('/beds');

// Initialise the bed timeout holder object
beds.once("value", function(snapshot){
  var hotels = snapshot.val();

  for (var i = 0; i < hotels.length; i++) {
    // push empty list to be filled with lists holding individual bed timeouts
    if(hotels[i]){
      hotelBedTimeouts.push([]);
      for(var j = 0; j < hotels[i].length; j++) {
        // this list will hold all timeouts for this bed
        hotelBedTimeouts[i].push({});
      }
    } else {
      hotelBedTimeouts.push(undefined);
    }
  }
});
不幸的是,这会导致我的整个firebase功能被删除:

$ firebase deploy --only functions

=== Deploying to 'company-23uzc'...

i  functions: deleting function scheduleFreeBed...
✔  functions[scheduleFreeBed]: Successful delete operation.
可以这样定义firebase函数吗

如何确保firebase函数始终能够访问后端代码中定义的某些变量

编辑:

这是我在Doug Stevenson的回答之后第一次尝试解决方案:

const hotelBedTimeouts = [];
var beds = db.ref('/beds');
const promise = beds.once("value");

// Frees a bed after a set amount of time
exports.scheduleFreeBed = functions.database.ref('/beds/{hotelIndex}/{bedIndex}/email').onUpdate( (snapshot, context) => {

  promise.then( (snapshot) => {
      var hotels = snapshot.val();

      for (var i = 0; i < hotels.length; i++) {
        // push empty list to be filled with lists holding individual bed timeouts
        if(hotels[i]){
          hotelBedTimeouts.push([]);
          for(var j = 0; j < hotels[i].length; j++) {
            // this list will hold all timeouts for this bed
            hotelBedTimeouts[i].push({});
          }
        } else {
          hotelBedTimeouts.push(undefined);
        }
      }
    });

  var originalEmail = snapshot.after.val();
  var hotelIndex = context.params.hotelIndex;
  var bedIndex = context.params.bedIndex;
  if (originalEmail === -1) {
    clearTimeout(hotelBedTimeouts[hotelIndex][bedIndex].timeoutFunc); // clear current timeoutfunc
    return 0; // Do nothing
  }

  // replace old timeout function
  hotelBedTimeouts[hotelIndex][bedIndex].timeoutFunc = setTimeout(function () { // ERROR HERE
    var bedRef = admin.database().ref(`/beds/${hotelIndex}/${bedIndex}`);
    bedRef.once("value", function(bedSnap){
      var bed = bedSnap.val();
      var booked = bed.booked;
      if (!booked) {
        var currentEmail = bed.email;
        // Check if current bed/email is the same as originalEmail
        if (currentEmail === originalEmail) {
          bedSnap.child("email").ref.set(-1, function() {
            console.log("Freed bed");
          });
        }
      }
    });
  }, 300000); // 5 min timeout


  return 0;
});
我已经在代码中的注释中标记了此错误的行


列表怎么还不能定义?

Firebase CLI不支持这种类型的函数定义。相反,您应该开始函数内部的初始工作,稍后缓存结果,这样就不必再次执行它。或者,您可以尝试开始工作,并保留函数稍后可以使用的承诺,如下所示:

const promise = doSomeInitialWork()  // returns a promise that resolves with the data

exports.scheduleFreeBed = functions.database.ref(...).onUpdate(change => {
    promise.then(results => {
        // work with the results of doSomeInitialWork() here
    })
})

谢谢你的回答。我不想在函数内部重新进行工作,只在加载函数时进行。这项工作包括初始化将由firebase函数填充的空数组和对象数组。因此,如果我将其重新初始化为空,我将丢失重要信息。我怎样才能解决这个问题?我的解决方案不能解决这个问题。它只执行一次工作,并重用承诺的结果。啊,因为承诺只能解决一次,谢谢!是的,你明白了。嗯,我尝试了你的解决方案,但我仍然有一个问题,在函数执行时,工作似乎没有完成。我在更新中发布了更多信息。
TypeError: Cannot read property '15' of undefined
const promise = doSomeInitialWork()  // returns a promise that resolves with the data

exports.scheduleFreeBed = functions.database.ref(...).onUpdate(change => {
    promise.then(results => {
        // work with the results of doSomeInitialWork() here
    })
})