Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/423.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何从另一个函数中的firebase函数中访问函数_Javascript_Firebase_Firebase Realtime Database - Fatal编程技术网

Javascript 如何从另一个函数中的firebase函数中访问函数

Javascript 如何从另一个函数中的firebase函数中访问函数,javascript,firebase,firebase-realtime-database,Javascript,Firebase,Firebase Realtime Database,我有一段代码,其中有三个函数。一个函数是go(),另一个是checkIfUserExists(),另一个是userExistsCallback()。go函数调用checkIfUserExists函数。Insider checkIfUserExists函数我调用一个firebase函数,然后需要调用UserExistScalBack()。但我无法从firebase函数内部访问UserExistScalBack async go() { var userId = 'ada'; this.c

我有一段代码,其中有三个函数。一个函数是go(),另一个是checkIfUserExists(),另一个是userExistsCallback()。go函数调用checkIfUserExists函数。Insider checkIfUserExists函数我调用一个firebase函数,然后需要调用UserExistScalBack()。但我无法从firebase函数内部访问UserExistScalBack

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

}

无效,因为它引用了封闭的
函数
,在本例中是您的
一次
回调

将您的
回调更改为不绑定此
一次即可:

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