【问题标题】:Return an array with multiple responses with Axios使用 Axios 返回具有多个响应的数组
【发布时间】:2021-06-22 01:00:26
【问题描述】:

我有一个函数可以获取一些股票的汇率:

export const getRates = (symbole1, symbole2, symbole3) => {
    
    const res = []

    axios.all([
        axios.get(`${baseUrl}/${symbole1}`),
        axios.get(`${baseUrl}/${symbole2}`),
        axios.get(`${baseUrl}/${symbole3}`)
    ])
        .then(axios.spread((data1, data2, data3) => {

            res.push(data1.data)
            res.push(data2.data)
            res.push(data3.data)
             return res
    }))
        .catch(
            err => console.log(err)
        )
}

在另一个文件中,我使用如下函数:

useEffect(() => {
        getRates('IBM', 'AAPL', 'MSFT')
            .then(res => {
                console.log(res)
                setStock(res)
            })
            .catch(err => {
                console.log(err)
            })
    }, [])

但是,这不起作用,因为第二个文件会引发此错误:

TypeError: 无法读取未定义的属性 'then'

这里有什么问题?你不能这样返回结果吗?还是有其他问题?

谢谢

【问题讨论】:

    标签: javascript reactjs axios


    【解决方案1】:

    您收到错误是因为您要求解决承诺,但只返回一个常规值。您可以设置另一个承诺以正确返回您的 then 会理解的内容 - 或者 - 您可以只返回承诺...

    export const getRates = (symbole1, symbole2, symbole3) => {
      return axios.all([
        axios.get(`${baseUrl}/${symbole1}`),
        axios.get(`${baseUrl}/${symbole2}`),
        axios.get(`${baseUrl}/${symbole3}`)
      ])
    
    }
    
    useEffect(() => {
      const res = []
      getRates('IBM', 'AAPL', 'MSFT')
        .then(axios.spread((data1, data2, data3) => {
          res.push(data1.data)
          res.push(data2.data)
          res.push(data3.data)
          console.log(res)
          setStock(res)
        }))
        .catch(
          err => console.log(err)
        )
    
    }, [])
    

    【讨论】:

      猜你喜欢
      • 2020-05-23
      • 2020-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-09
      • 2018-11-26
      • 1970-01-01
      相关资源
      最近更新 更多