Async 和 Await 在 Axios React 中不起作用

Jot*_*ota 3 javascript async-await reactjs axios

我有个问题:

我希望我axios提出申请,并在提出申请后将this.setState结果保存在变量中。

我的代码:

componentDidMount() {
  let mails = [];
  axios.get('/api/employee/fulano')
    .then(res => this.setState({
      employees: res.data
    }, () => {

      this.state.employees.map(i => {
        async axios.get(`/api/status/${i.mail}`)
          .then(res => {
            mails.push(res.data)
            await this.setState({
              mails: mails
            })
          })
          .catch(err => console.log(err))
      })
    }))
    .catch(err => console.log(err))
}
Run Code Online (Sandbox Code Playgroud)

但它给出了错误语法。

最佳解释:我想将地图的所有结果保存在变量中mails,然后使用 来setState更改一次的结果。

有人可以告诉我我在哪里徘徊吗?请。

Shu*_*tri 5

您在错误的地方使用了异步等待。async关键字必须用于包含异步函数的函数

await关键字需要用于返回 a 的表达式Promise,尽管是setStateis async,但它不会返回 Promise,因此await无法使用它

你的解决方案看起来像

componentDidMount() {
  let mails = [];
  axios.get('/api/employee/fulano')
    .then(res => this.setState({
      employees: res.data
    }, async () => {

      const mails = await Promise.all(this.state.employees.map(async (i) => { // map function contains async code
        try {
             const res = await axios.get(`/api/status/${i.mail}`)
             return res.data;
        } catch(err) { 
            console.log(err)
        }
      })
      this.setState({ mails })
    }))
    .catch(err => console.log(err))
}
Run Code Online (Sandbox Code Playgroud)