无法从从 Firebase 获取的 class 方法获取数据
Cannot get data from class method taken from Firebase
我很难解决我的问题。我已连接到 Firebase,并尝试设置连接并检查名称是否在数据库中。
class Db {
connect (path) {
const db = firebase.firestore();
const docRef = db.doc(path);
return docRef;
}
exist (name, path) {
this.connect(path).get()
.then(querySnapshot => {
console.log(querySnapshot.data().Users);
const users = querySnapshot.data().Users;
// return users;
if (users.indexOf(name) > -1) {
console.log('yes');
return true
} else {
console.log('no');
return false
}
})
.catch(e => {
console.log(e);
})
}
}
let databaseurl = '2048/database';
let database = new Db();
console.log(database.exist('kytek', databaseurl)); //undefined
从控制台日志我得到 undefined
但是控制台日志 return 一个数组,我不确定为什么......
在 if:
之前与 return 分开
console.log(querySnapshot.data().Users);
const users = querySnapshot.data().Users;
return users;
和consol.logreturns数组
但是 return
returning undefined
有任何想法吗?
您没有获得 true/false 值,因为您编写的 exist()
函数是异步的,并且您没有 return 内部函数。如果你想 return 来自内部 this.connect().get()
函数的数据,你需要 return 那个外部函数...我的意思是:
exist (name, path) {
return this.connect(path).get()
.then(querySnapshot => {
// etc... rest of function here
如果这对您不起作用,您可能还必须将函数标记为 async
并使用 await
等待接收结果:
async exist (name, path) {
return this.connect(path).get()
.then(querySnapshot => {
// etc... rest of function here
let databaseurl = '2048/database';
let database = new Db();
let result = await database.exist('kytek', databaseurl);
console.log(result);
我很难解决我的问题。我已连接到 Firebase,并尝试设置连接并检查名称是否在数据库中。
class Db {
connect (path) {
const db = firebase.firestore();
const docRef = db.doc(path);
return docRef;
}
exist (name, path) {
this.connect(path).get()
.then(querySnapshot => {
console.log(querySnapshot.data().Users);
const users = querySnapshot.data().Users;
// return users;
if (users.indexOf(name) > -1) {
console.log('yes');
return true
} else {
console.log('no');
return false
}
})
.catch(e => {
console.log(e);
})
}
}
let databaseurl = '2048/database';
let database = new Db();
console.log(database.exist('kytek', databaseurl)); //undefined
从控制台日志我得到 undefined
但是控制台日志 return 一个数组,我不确定为什么......
在 if:
console.log(querySnapshot.data().Users);
const users = querySnapshot.data().Users;
return users;
和consol.logreturns数组
但是 return
returning undefined
有任何想法吗?
您没有获得 true/false 值,因为您编写的 exist()
函数是异步的,并且您没有 return 内部函数。如果你想 return 来自内部 this.connect().get()
函数的数据,你需要 return 那个外部函数...我的意思是:
exist (name, path) {
return this.connect(path).get()
.then(querySnapshot => {
// etc... rest of function here
如果这对您不起作用,您可能还必须将函数标记为 async
并使用 await
等待接收结果:
async exist (name, path) {
return this.connect(path).get()
.then(querySnapshot => {
// etc... rest of function here
let databaseurl = '2048/database';
let database = new Db();
let result = await database.exist('kytek', databaseurl);
console.log(result);