微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在React中异步/等待

如何解决在React中异步/等待

我正在尝试在我的React应用程序中使用async / await。从我在这代码中阅读的内容来看,该功能应该先运行,然后console.log将等待该功能完成...

async postSelectedHandler() {
    await this.getInServiceVenues();
    console.log('Updated In Service 2: '+this.state.venuesInService);
}

也许我错了,但是我要做的是确保该功能先在console.log运行之前运行,但仍在异步运行。

getInServiceVenues的代码...

getInServiceVenues = () =>{
    this.setState({ loading: true });
    let bodyInService = [];
    let iterationInService = 0;
    let RequestingNetworkOperatorList = [];
    let updatedVenuesInService = [];
    
    axios.post( '/propertymanagement/listVenues',bodyInService,{
        headers: {}
    })
        .then( response => {
            if (this._isMounted) {
            this.setState({loading: false});
            this.setState({venues: []});
            const venuesInService = response.data.InServiceVenueList;
            let venueIdInService = null;
            
            bodyInService.push(venuesInService);
            
            bodyInService.forEach(val=>{
                    venueIdInService = Object.keys(bodyInService[0]);
                    //console.log(venueId);
                })
            if(this.state.venuesInService!==[]){
                    this.setState({venuesInService:[]});
                }
            venueIdInService.forEach(val=>{
                
                updatedVenuesInService = bodyInService.map(venueInService => {
                    return {
                        ...venueInService[venueIdInService[iterationInService]],iterationInService,RequestingNetworkOperatorList
                    }

                });
                
                this.setState({
                    venuesInService:[...this.state.venuesInService,updatedVenuesInService]
                });
                iterationInService = iterationInService + 1;
                
            })
            console.log('Updated In Service 1: '+this.state.venuesInService);
        }} )
        .catch(error => {
            console.log(error);
            this.setState({error: true});
        });
    }

解决方法

问题是,您正在调用的函数没有返回promise,因此该位实际上是同步运行的。

在此行的开头添加一个return

axios.post( '/propertymanagement/listVenues',bodyInService,

它应该可以工作。

您还可以选择将其转换为也使用asyncawait,它们在功能上是相同的:

getInServiceVenues = async () =>{
    this.setState({ loading: true });
    let bodyInService = [];
    let iterationInService = 0;
    let RequestingNetworkOperatorList = [];
    let updatedVenuesInService = [];
    
    try {
      const response = await axios.post( '/propertymanagement/listVenues',{
          headers: {}
      });
    
      // everything from your then()
    } catch (error) {
      // everything from your catch()
    }
}    
,

您应该在getInServiceVenues函数中使用await / async,将thencatch更改为同步操作。

使用try / catch块并返回axios的结果,而不是使用thencatch,然后您就无需在此函数之外使用async / await。

类似下面的代码

getInServiceVenues = async () =>{
    this.setState({ loading: true });
    let bodyInService = [];
    let iterationInService = 0;
    let RequestingNetworkOperatorList = [];
    let updatedVenuesInService = [];
    
    try { 
        const result = axios.post( '/propertymanagement/listVenues',{headers: {}})     
        if (this._isMounted) {
            this.setState({loading: false});
            this.setState({venues: []});
            const venuesInService = response.data.InServiceVenueList;
            let venueIdInService = null;
            
            bodyInService.push(venuesInService);
            
            bodyInService.forEach(val=>{
                    venueIdInService = Object.keys(bodyInService[0]);
                    //console.log(venueId);
            })

            if(this.state.venuesInService!==[]){
                    this.setState({venuesInService:[]});
            }
            venueIdInService.forEach(val => {
                updatedVenuesInService = bodyInService.map(
                  venueInService => {
                    return {
                        ...venueInService[
                            venueIdInService[iterationInService]
                        ],iterationInService,RequestingNetworkOperatorList
                    }
             });
                
                this.setState({
                    venuesInService:[...this.state.venuesInService,updatedVenuesInService]
                });
                iterationInService = iterationInService + 1;
                
            })
            console.log('Updated In Service 1:'+this.state.venuesInService);
    } catch(error) {
        console.log(error);
        this.setState({error: true});
    };
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。