React中的异步功能不会等待

时间:2019-05-07 18:42:49

标签: javascript reactjs

我创建了一个联系表单组件。有一个异步handleSend函数可以正常工作。然后,我在其中添加了一个额外的异步函数调用(postalCodesDistance)。

    async handleSend() {
        this.setState({isSending:true})
        const mailerPath = this.context.path+'mail.php';
        let dane = {}

      this.postalCodesDistance(this.context.companyCoords,this.state.customerCoords).then(distance=>{
            if(distance!==undefined){
                dane.distance = distance
            }
        })

        const form = await axios.post( mailerPath, dane).then(res => {
            this.setState({sendingError: false, isSending: false})
        }).catch(err => { 
            console.log(err) 
            this.setState({sendingError: true, isSending: false})
        })
    };
    async postalCodesDistance(postalCodeA, postalCodeB){
        try{
            const countryA = this.checkPostalCode(postalCodeA)
            const countryB = this.checkPostalCode(postalCodeB)
            if( !countryA || !countryB){
                return console.log("At least one of the arguments is not valid")
            } 
            const postalCodeA_radians = await this.findCoords(postalCodeA,countryA)
            const postalCodeB_radians = await this.findCoords(postalCodeB,countryB)
            return this.calculateCoordsDistance(postalCodeA_radians,postalCodeB_radians)
        }catch(err){
            console.log("At least on of the given postal codes couldn't be found",err)
        }
    }

我遇到的问题是该函数不等待findCoords结果(另一个异步函数),并且我总是得到未定义的postalCodeA_radians和postalCodeB_radians值。

checkPostalCode不是异步函数。它只是检查一些正则表达式。在findCoords函数中,有一个axios get请求,例如:

 async findCoords(postalCode,country){
    ... // some code with defining Url
    return await axios.get(Url)
        .then(data=>{
            if(data.data!==undefined){
                if(data.data[0].display_name.includes(country)){
                    return [data.data[0].lat*(Math.PI/180), data.data[0].lon*Math.PI/180]
                }
            }
        })
        .catch(err=>{
            console.log(err)
        })
}

当我使用简单节点准备这些功能时,它们可以正常工作。当我尝试将它们放入React应用程序的ContactForm类组件时遇到问题。首先,我认为这是组件生命周期的问题,但是我使用onClick = {this.onContinue}

在窗体下方创建了一个按钮
     async onContinue(){
        const send = await this.handleSend()
    }

它仍然无法正常工作。

0 个答案:

没有答案