简体   繁体   中英

Async/Await in React

I'm trying to utilize async/await in my React app. From what I've been reading in this code the function should run first and then the console.log will wait for the function to finish...

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

Maybe I'm wrong but what I'm trying to do is make sure the function runs first before the console.log runs but it's still running asynchronously.

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

The problem is, the function you are calling isn't returning a promise so that bit is essentially running synchronously.

Add a return to the beginning of this line:

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

and it should work.

You can also optionally convert it to use async and await too, which is functionally the same:

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

You should use await/async in you getInServiceVenues function, change the then and catch to a synchronous operation.

Instead of using then and catch , use try/catch block and return the result of axios and then you dont need to use async/await outside this function.

Something like the code below

getInServiceVenues = async () =>{
    this.setState({ loading: true });
    let bodyInService = [];
    let iterationInService = 0;
    let RequestingNetworkOperatorList = [];
    let updatedVenuesInService = [];
    
    try { 
        const result = axios.post( '/propertymanagement/listVenues', 
        bodyInService, {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});
    };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM