如何在javascript类中的另一个函数内调用异步函数?
我试图在类内调用异步函数,但不断得到一个错误,该错误如何在javascript类中的另一个函数内调用异步函数?,javascript,class,async-await,Javascript,Class,Async Await,我试图在类内调用异步函数,但不断得到一个错误,该错误this.getcategory.then不是函数 在category.js:21 我有一个表单,管理员使用它向数据库中添加更多类别categform.addEventListener('submit',e=>{此行将侦听submit事件,然后使用下面的代码段获取数据并将其插入数据库 super.postText("../includes/getcategoy.inc.php", categformData) .then
this.getcategory.then不是函数
在category.js:21
我有一个表单,管理员使用它向数据库中添加更多类别categform.addEventListener('submit',e=>{
此行将侦听submit事件,然后使用下面的代码段获取数据并将其插入数据库
super.postText("../includes/getcategoy.inc.php", categformData)
.then(res => {
console.log(res);
// 1. if the results are ok fetch the fresh data from the database
this.getcategory.then(
res => {
console.log(res);
}
)
}).catch((error) => {
console.error('Error:', error);
});
现在,上面的代码返回一个承诺,然后如果结果正常,我调用同一类中的另一个函数,从数据库获取最新数据。函数是this.getcategory
记住,我在中调用函数,然后得到一个错误。我在中调用的原因是then是因为我们只希望在将数据发送到数据库中的问题得到解决后才能执行它。但是当我在第一个函数之外调用它时,我没有得到一个错误。。 如果您查看catch块的后面,我已经注释掉了它。如果我在那里调用它,我不会得到错误。但是我不想在那里调用它。记住函数返回一个承诺,并且它被定义为类中的最后一个函数 如何解决这个问题,下面是全部代码
import { FETCH } from "./fetch.js";
class CATEGORY extends FETCH {
constructor() {
super()
}
listencategory() {
//1. Listen for the button click
const categform = document.getElementById('categotyform');
categform.addEventListener('submit', e => {
e.preventDefault();
//2. get the data from form
const categformData = new FormData(categform);
super.postText("../includes/getcategoy.inc.php", categformData)
.then(res => {
// console.log(res);
// 1. if the results are ok fetch the fresh data from the database
this.getcategory.then(
res => {
console.log(res);
}
)
}).catch((error) => {
console.error('Error:', error);
});
});
//this.getcategory().then(res=>{
// console.log(res);
//
//})
}
async getcategory() {
try {
const results = await super.get("../includes/getcategoy.inc.php");
return results;
} catch (error) {
console.log(error);
}
}
}
const categ = new CATEGORY;
categ.listencategory();
我正在尝试获取由异步getcategory()返回的数据getcategory是一个
异步
函数,应该进行如下函数调用
this.getcategory().then(
res => {
console.log(res);
}
)
此链接帮助您有效地创建和使用承诺。
请提供
/fetch.js
的内容。getcategory现在在类中,问题是当我在/1之后调用它时。如果结果正常,从数据库中获取新数据
我会得到一个错误,它不是一个函数,但如果我在eventlistener之外调用它,它会工作getcategory将获取所有的c数据库中的类别,我需要在新数据插入数据库后调用它,问题是我需要在解决另一个承诺后调用它。