【问题标题】:Axios API call returning Promise object instead of result?Axios API 调用返回 Promise 对象而不是结果?
【发布时间】:2026-01-05 18:55:01
【问题描述】:

在开始之前,让我说我是 Javascript 新手,对 axios API 调用非常陌生,所以我可能犯了一个菜鸟错误......

我有这个函数getObjects() 用于映射数组并从 Axios API 调用返回数据。 API 调用和 map 函数都在工作,但我得到的是一个 Promise 对象,而不是我想要获取的数据。

我认为这是因为在有足够的时间实际获取数据之前返回了数据,但不确定如何解决?我尝试了.setTimeout(),但这似乎不起作用。

  getObjects() {
    let newsItems = this.state.arrayofids.map((index) => {
      let resultOfIndex = axios.get(`https:\/\/hacker-news.firebaseio.com/v0/item/${index}.json`).then((res) => {
          let data = res.data;
          //console.log(data.by); // this prints the correct byline, but
                              // all the bylines are printed after
                              // the console.log below...
          if (!data.hasOwnProperty('text')) return data;
        }); /// end of axios request
  return resultOfIndex;
    }); /// end of map
    /// ideally this would end in an array of response objects but instead i'm getting an array of promises...
    console.log(newsItems);
  }

(额外的转义字符是为了我的文本编辑器的好处。)

Here's a link to a codepen with the issue - 打开控制台查看问题。这是一个 React 项目,但我认为任何 React 的东西都不是问题。 编辑: Codepen 使用axios.all 链接到工作解决方案,如下所示

谢谢!

编辑:这是我的工作解决方案。

getObjects() {
  let axiosArr = [];
  axios.all(this.state.arrayofids.map((id) => {
      return axios.get(`https:\/\/hacker-news.firebaseio.com/v0/item/${id}.json`)
    })).then((res) => {
      for (let i = 0; i < this.state.arrayofids.length; i++) {
        axiosArr.push(<li key={i} data-url={res[i].data.url} onClick={(e) => this.displayTheNews(e)}>{res[i].data.title}</li>);
      }
      if (axiosArr.length == this.state.arrayofids.length) {
        this.setState({arrayofdata: axiosArr});
        console.log('state is set!');
      }
    })
 }

【问题讨论】:

  • 不是专家,但我已经使用了一段时间。我很确定它只返回承诺,因为有一个 axios.all 函数。你必须弄清楚 then 中的逻辑,我建议使用 this.setState 或 redux 等价物。您实际上可能想查看axios.all 而不是进行此映射。
  • @A.Lau 哦,太好了,这绝对让我走上了正确的道路。非常感谢。
  • 我会把它作为答案然后

标签: javascript reactjs axios


【解决方案1】:

axios.all 函数应该更适合您当前的场景。

【讨论】:

    【解决方案2】:

    您的console.log 正在立即执行,而不是等待请求完成,因为它们不是同步的。您必须等待所有回复才能console.log

    选项 1(艰难的方式): 用

    替换你的console.log
    newsItems.forEach((promise, index) => {
      promise.then((object)=>{
        newsItems[index] = object
        if (index+1 == newsItems.length) {
          console.log(newsItems)
        }
      })
    })
    


    选项 2(更好的方法): 使用axios.all

      getObjects() {
        axios.all(this.state.arrayofids.map((id) => {
          return axios.get(`https:\/\/hacker-news.firebaseio.com/v0/item/${id}.json`)
        })).then((res) => {
          console.log(res)
        })
      }
    

    顺便说一句,我肯定会建议改变

    this.state.arrayofids.map((index) => {
          let resultOfIndex = axios.get(`https:\/\/hacker-news.firebaseio.com/v0/item/${index}.json`)...
    

    被称为id 而不是index

    【讨论】:

      最近更新 更多