await不等待子函数首先在react中执行


async fetchJobs() {
this.setState({ isFetching: true }, async () => {
try{
debugger;
console.log("fetching Jobs");
var body = {
page: this.state.page,
sortBy: this.state.sortBy,
comparator: this.state.comparator,
batch: this.state.batch,
role: this.state.role,
companies: this.state.selectedCompanies
}
var job = await axios({
method: 'get',
url: `${process.env.PUBLIC_URL}/api/page_job?page=${this.state.page}`,
params: body
});
const page_jobs = job.data.page;
const jc = job.data.count;

const jobcount = parseInt(jc);

this.setState({
jobs: page_jobs,
jobcount: jobcount
}, () => {
this.getPagination();
if (this.refJobs.current)
this.refJobs.current.scrollTop = 0;
});
debugger;
console.log("fetched jobs");
}
catch(error){
console.log("err1");
throw error;
}
finally{
this.setState({ isFetching: false });
}
});    
}
filterHandler = async (body) => {
this.setState({
page: 1,
sortBy: body.sortBy,
comparator: body.comparator,
batch: body.batch,
role: body.role,
selectedCompanies: body.selectedCompanies
}, async () => {
tr{
await this.fetchJobs();
console.log("not catching error");
}
catch(error){
console.log("err2");
throw error;
}
})
}

当通过await调用filterHandler函数时,它给出的输出如下:获取工作未捕获错误获取工作,而不是:获取工作获取工作未捕获错误我无法理解如何使用async/await来获得所需的输出。正如async/await应该的那样停止父函数,执行子函数,然后返回父函数

当你await fetchJobs时,你没有等待fetch的承诺。

试试这个:

async fetchJobs() {
this.setState({ isFetching: true });
try {
// ...
}
catch(error) {
// ...
}
finally {
// ...
}
}

另一个选项是显式地生成和解析承诺:

fetchJobs = () => new Promise( (resolve, reject) => {
this.setState({ isFetching: true }, async () => {
try {
// ...
debugger;
console.log("fetched jobs");
resolve(jobcount); // For example...
}
catch(error) {
// ...
reject(error);
}
finally {
// Not sure if this is going to be executed, probably not
this.setState({ isFetching: false });
}
});
})

最新更新