如何从Firebase函数内部访问另一个函数内部的函数

时间:2019-01-30 16:51:31

标签: javascript firebase firebase-realtime-database

我有一段代码,其中包含三个功能。一个函数是go(),另一个函数是checkIfUserExists(),另一个函数是userExistsCallback()。 go函数调用checkIfUserExists函数。内部人员checkIfUserExists函数我调用了一个Firebase函数,然后需要调用userExistsCallback()。但是我无法从该Firebase函数内部访问userExistsCallback。

async go() {

  var userId = 'ada';
  this.checkIfUserExists(userId); // this is working. It perfectly calls the function
  console.log('the go function');
}


async userExistsCallback(userId, exists) {
  if (exists) {
    console.log(' exists!');
 } else {
    console.log(' does not exist!');
  }
  console.log('function userExistsCallback ends');
}


async checkIfUserExists(userId) {

  var usersRef = firebase.database().ref("news/");
  usersRef.child(userId).once('value', function(snapshot) {
    var exists = (snapshot.val() !== null);
    this.userExistsCallback(userId, exists); // this is not working. 
    console.log('function checkIfUserExists');
  });

}

1 个答案:

答案 0 :(得分:1)

this不起作用,因为它引用了封闭的function,在本例中为您的once回调。

将您的once回调更改为一个arrow function,该绑定不会绑定this,您可以这样做:

async checkIfUserExists(userId) {

  var usersRef = firebase.database().ref("news/");
  usersRef.child(userId).once('value', (snapshot) => {
    // `this` now refers to `window` where your global functions
    // are attached.
    var exists = (snapshot.val() !== null);
    this.userExistsCallback(userId, exists); // this is not working. 
    console.log('function checkIfUserExists');
  });
}
相关问题