【问题标题】:Async and Await not working in Axios React异步和等待在 Axios React 中不起作用
【发布时间】:2019-03-17 22:52:45
【问题描述】:

我有一个问题:

我希望我的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))
}

但它给出了错误语法。

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

谁能告诉我我在哪里徘徊?请。

【问题讨论】:

  • 如果您可以使用thencatch,为什么还要尝试使用async/await
  • 为解决您的实际问题,您正在寻找Promise.all

标签: javascript reactjs async-await axios


【解决方案1】:

这应该可行:

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

           this.state.employees.map(i => {
           axios.get(`/api/status/${i.mail}`)
             .then( async (res) => { // Fix occurred here
                let mails = [].concat(res.data)
                await this.setState({
                  mails: mails
             })
          })
          .catch(err => console.log(err))
        })
      }))
         .catch(err => console.log(err))
     }

【讨论】:

  • 欢迎来到stackoverflow!请详细说明一下。给出的另一个答案看起来更好,即使它是在你之后给出的:这是因为有一个解释。
【解决方案2】:

你把async放错地方了

async 应该放在函数定义中,而不是函数调用中

componentDidMount() {
    let mails = [];
    axios.get('/api/employee/fulano')
    .then(res => this.setState({
        employees: res.data
    }, () => {
        this.state.employees.map(i => {
            axios.get(`/api/status/${i.mail}`)
            .then(async (res) => {
                mails.push(res.data)
                await this.setState({
                    mails: mails
                })
            })
            .catch(err => console.log(err))
        })
    }))
    .catch(err => console.log(err))
}

【讨论】:

    【解决方案3】:

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

    await 关键字需要用于返回 Promise 的表达式,虽然 setStateasync,但它不返回 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))
    }
    

    【讨论】:

    • 你好,谢谢你的回答,我很高兴这个..但是给了:await is a reserved word (20:22),为什么?
    • @Jota,抱歉,在 setState 回调函数中缺少 async 关键字,更新了我的答案
    【解决方案4】:

    async/await.then/.catch 混合使用不是一个好习惯。而是使用其中一种。这是一个示例,说明如何使用 ONLY async/awaitONLY 一个 this.setState()(参考 Promise.each 函数):

    componentDidMount = async () => {
      try {    
        const { data: employees } = await axios.get('/api/employee/fulano'); // get employees data from API and set res.data to "employees" (es6 destructing + alias)
    
        const mails = []; // initialize variable mails as an empty array
    
        await Promise.each(employees, async ({ mail }) => { // Promise.each is an asynchronous Promise loop function offered by a third party package called "bluebird"
          try {
           const { data } = await axios.get(`/api/status/${mail}`) // fetch mail status data
           mails.push(data); // push found data into mails array, then loop back until all mail has been iterated over
          } catch (err) { console.error(err); }
        })
    
        // optional: add a check to see if mails are present and not empty, otherwise throw an error.
    
        this.setState({ employees, mails }); // set employees and mails to state
      } catch (err) { console.error(err); }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 2018-01-02
      • 1970-01-01
      • 2018-01-27
      相关资源
      最近更新 更多