简体   繁体   English

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

[英]How to access a function from inside a firebase function that is inside another function

I have a piece of code where there are three functions.我有一段代码,其中有三个功能。 One function is go(), another one is checkIfUserExists() and another one is userExistsCallback().一个函数是 go(),另一个是 checkIfUserExists(),另一个是 userExistsCallback()。 The go function calls the checkIfUserExists function. go 函数调用 checkIfUserExists 函数。 Insider checkIfUserExists function I call a firebase function which then needs to call userExistsCallback(). Insider checkIfUserExists 函数我调用了一个 firebase 函数,然后需要调用 userExistsCallback()。 But I am not being able to access userExistsCallback from inside that firebase function.但是我无法从该 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');
  });

}

this is not working because it refers to the enclosing function , in this case your once callback. this不起作用,因为它指的是封闭function ,在这种情况下是您的once回调。

Change your once callback to an arrow function which doesn't bind this and you're good to go:将您的once回调更改为不绑定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');
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM