Javascript 等待而不是等待子函数在react中首先执行
当通过WAIT调用filterHandler函数时,其输出为: 找工作 未捕获错误 找工作, 而不是: 找工作 找到工作 未捕获错误 我无法理解如何使用async/await获得所需的输出。async/await应该是Javascript 等待而不是等待子函数在react中首先执行,javascript,asynchronous,async-await,Javascript,Asynchronous,Async Await,当通过WAIT调用filterHandler函数时,其输出为: 找工作 未捕获错误 找工作, 而不是: 找工作 找到工作 未捕获错误 我无法理解如何使用async/await获得所需的输出。async/await应该是 已停止父函数,执行子函数,然后返回父函数。当您等待fetchJobs时,您不是在等待fetch承诺 试试这个: async fetchJobs(){ this.setState({isFetching:true}); 试一试{ // ... } 捕获(错误){ // ... }
已停止父函数,执行子函数,然后返回父函数。当您等待fetchJobs时,您不是在等待fetch承诺 试试这个:
async fetchJobs(){
this.setState({isFetching:true});
试一试{
// ...
}
捕获(错误){
// ...
}
最后{
// ...
}
}
另一种选择是显式生成和解析承诺:
fetchJobs=()=>新承诺((解析、拒绝)=>{
this.setState({isFetching:true},async()=>{
试一试{
// ...
调试器;
log(“获取的作业”);
解析(作业计数);//例如。。。
}
捕获(错误){
// ...
拒绝(错误);
}
最后{
//不确定这是否会被执行,可能不会
this.setState({isFetching:false});
}
});
})
如果我从setState中删除回调,会不会造成问题,因为它会导致在seState完成之前执行try块?我不这么认为。第一个setState
将在其余部分之前执行,其结果将在触发fetch
的同一渲染中可用。我了解到setState本质上是异步的,如果我们需要在之后执行语句,我们需要将它们放入回调中。另外,我仍然不清楚为什么将try/catch块放在回调之外会使它工作。提前感谢:-)如果这是您的雇主强制执行的,请使用明确的承诺
版本。如果没有,那么第一个应该很好。您还可以解释一下为什么将try/catch块放在回调之外会使它工作吗?
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;
}
})
}