我正在尝试在类内调用异步函数,但始终收到this.getcategory.then is not a function
at 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);
});
现在上面的代码返回一个Promise,如果结果正确,我将调用同一类中的另一个函数以获取数据库的最新数据。功能是this.getcategory
,请记住我正在 then 内部调用该函数,并收到错误消息。我之所以在然后内部进行调用的原因是,仅希望在将数据发送到数据库后才执行它。
但是当我在第一个函数之外调用它时,我没有收到错误。
如果您只是在 catch块之后看,我已将其注释掉。如果我在那叫,我不会出错。但我不想在那叫它。记住该函数返回一个promise,它被定义为类中的最后一个函数
我该如何解决这个问题,下面是整个代码
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();
我正在尝试获取 async getcategory()
返回的数据答案 0 :(得分:0)
getcategory是一个Async
函数,应按如下所示进行函数调用。
this.getcategory().then(
res => {
console.log(res);
}
)
此链接可帮助您有效创建和使用承诺。 Async functions - making promises friendly