简体   繁体   English

Axios API调用返回Promise对象而不是结果?

[英]Axios API call returning Promise object instead of result?

Before I start, let me say that I'm new to Javascript and very new to axios API calls, so I'm probably making a rookie mistake... 在开始之前,请允许我说我是Javascript的新手,并且对axios API调用很新,所以我可能会犯一个菜鸟错误......

I have this function getObjects() that's meant to map over an array and return the data from an Axios API call. 我有这个函数getObjects() ,它意味着映射数组并从Axios API调用返回数据。 The API call and map function are both working, but I'm getting a Promise object instead of the data I'm trying to get. API调用和map函数都正常工作,但我得到的是Promise对象而不是我想要的数据。

I figure this is because the data is returned before there's enough time to actually get it, but not sure how to fix? 我认为这是因为在有足够的时间实际获取数据之前返回数据,但不确定如何修复? I tried a .setTimeout() , but that didn't seem to work. 我尝试了.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);
  }

(The extra escape characters are for my text editor's benefit.) (额外的转义字符是我的文本编辑器的好处。)

Here's a link to a codepen with the issue - open up the console to see the problem. 这是一个带有问题的codepen的链接 - 打开控制台以查看问题。 It's a React project but I don't think any of the React stuff is the issue. 这是一个React项目,但我不认为任何React的东西都是问题。 EDIT: Codepen is link to working solution using axios.all as suggested below 编辑: Codepen是使用axios.all链接到工作解决方案,如下所示

Thanks! 谢谢!

EDIT: Here is my working solution. 编辑:这是我的工作解决方案。

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函数应该更适合您当前的场景。

Your console.log is executing immediately, rather than waiting for the requests to finish, because they are not synchronous. 您的console.log正在立即执行,而不是等待请求完成,因为它们不是同步的。 You have to wait for all the responses before you console.log . 您必须在console.log之前等待所有响应。

OPTION 1 (the hard way): replace your console.log with 选项1 (困难的方法):用你的console.log替换

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


OPTION 2 (the better way): using axios.all 选项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)
    })
  }

by the way, I would definitely reccommend changing 顺便说一句,我肯定会推荐改变

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

to be called id instead of index 被称为id而不是index

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM