等待不等待子函数在反应中首先执行

时间:2021-01-24 19:17:30

标签: javascript asynchronous async-await

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 来获得所需的输出。作为异步/等待应该 已经停止了父函数,执行了子函数,然后返回到父函数。

1 个答案:

答案 0 :(得分:1)

当您 await fetchJobs 时,您不是在等待 fetch 承诺。

试试这个:

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

另一种选择是显式生成和解析 Promise:

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 });
    }
  });
})