如何将我的方法重写为异步/等待?

时间:2019-03-29 13:09:59

标签: javascript ajax reactjs async-await axios

在我的react应用程序中,我正在axios的帮助下向服务器发出发布请求:

 onSubmit = (results) => {
     axios.post("http://localhost:8080/simulate/", results)
      .then( (response) => this.setState({results: response.data.results}))
      .catch( (error) => this.setState({results: error.response.data, hasError: true})
      ); 
  }

如何将这种方法重写为async/await

1 个答案:

答案 0 :(得分:2)

onSubmit = async (results) => {
  try {
    const response = await axios.post("http://localhost:8080/simulate/", results)
    this.setState({results: response.data.results})
  } catch (error) {
    this.setState({results: error.response.data, hasError: true})
  }
}

编辑-不使用Axios

如果您不想使用Axios,则可以使用fetch api

onSubmit = async (results) => {
  try {
    const response = await fetch("http://localhost:8080/simulate/", {
      method: 'POST',
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(results)
    })
    const { data } = await response.json()
    this.setState({results: data.results})
  } catch (error) {
    this.setState({results: error.response.data, hasError: true})
  }
}