Javascript 如何从另一个函数中的firebase函数中访问函数
我有一段代码,其中有三个函数。一个函数是go(),另一个是checkIfUserExists(),另一个是userExistsCallback()。go函数调用checkIfUserExists函数。Insider checkIfUserExists函数我调用一个firebase函数,然后需要调用UserExistScalBack()。但我无法从firebase函数内部访问UserExistScalBackJavascript 如何从另一个函数中的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
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');
});
}