【发布时间】:2019-12-30 00:51:56
【问题描述】:
我正在尝试在类中调用异步函数,但不断收到this.getcategory.then is not a function
at category.js:21 的错误
我有一个表单,管理员使用该表单将更多类别添加到数据库中。 categform.addEventListener('submit', e => { 这一行将监听提交事件,然后使用下面的代码 sn-p 获取数据并插入到数据库中
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 中调用该函数并且出现错误。我在 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()
返回的数据【问题讨论】:
-
请提供
./fetch.js的内容。 -
getcategory 在类内,现在问题是当我在
// 1. if the results are ok fetch the fresh data from the database之后调用它时,我得到一个错误,它不是一个函数,但如果我在事件监听器之外调用它,它可以工作 -
getcategory 是从数据库中获取所有类别,需要在新数据插入数据库后调用它,
标签: javascript class async-await