Typescript 在其他函数中调用异步函数
我在异步函数方面遇到问题。我有以下功能,可以正常工作,基本上可以在firebase实时数据库中搜索匹配的用户名:Typescript 在其他函数中调用异步函数,typescript,asynchronous,ionic-framework,firebase-realtime-database,Typescript,Asynchronous,Ionic Framework,Firebase Realtime Database,我在异步函数方面遇到问题。我有以下功能,可以正常工作,基本上可以在firebase实时数据库中搜索匹配的用户名: static async getSnapshot(fc: FormControl){ let isPresent:boolean = false; await firebase.database().ref().child("users").orderByChild("username") .equalTo(fc.v
static async getSnapshot(fc: FormControl){
let isPresent:boolean = false;
await firebase.database().ref().child("users").orderByChild("username")
.equalTo(fc.value)
.once("value", snapshot => {
}).then((data)=> {
if(data.exists())
isPresent = true;
else
isPresent = false;
});
console.log(isPresent);
return isPresent;
}
问题是,当我在另一个函数中调用此函数时,我希望根据结果执行其他操作:
static async validUsername(fc: FormControl){
try{
let bool:boolean =await this.getSnapshot(fc.value)
if(bool===true)
return ({validUsername: true});
else{
return (null);
}
}catch(e){
console.log(e)
}
}
该行:
let bool:boolean =await this.getSnapshot(fc.value)
返回以下错误:
TypeError: Cannot read property 'getSnapshot' of undefined
如何修改我的函数?提前感谢您的回复
此
通常指一个实例。静态方法不属于任何实例,因此此
在它们中没有意义
要解决您的问题,只需使用您的类名而不是this
。例如
class APIHandlers {
static async getSnapshot {...}
static async validUsername(fc: FormControl){
try{
let bool:boolean = await APIHandlers.getSnapshot(fc.value);
...
}
}
这个代码经过测试了吗?操场上有件有趣的事这似乎很管用:。我对你的ts很好奇。config@EiriniGraonidou如果我们使用箭头函数,就会出现上面提到的错误OP,这将非常有意义。但OP似乎没有使用箭头功能。无论如何,使用类而不是实例引用静态方法是有意义的。但我更愿意将此视为一个警告。您是否可以在实际调用
validUsername
的位置添加代码?