YouTube API返回的数据似乎不可变?

时间:2018-06-13 08:08:01

标签: javascript react-native youtube-api axios



 onSearch = async () => {
    const query = qs.stringify({ ...API_QUERY_PARAMS, q: this.state.searchString });
    const url = `https://www.googleapis.com/youtube/v3/search?${query}`
    
    const { data } = await axios.get(url);
    
    data.items.forEach(async vid => {
      let id = vid.id.videoId; //Individual video ID
      const individualQuery = qs.stringify({ ...INDIVIDUAL_API_QUERY_PARAMS, id  });
      const individualURL = `https://www.googleapis.com/youtube/v3/videos?${individualQuery}`;
      
      const { data } = await axios.get(individualURL);
      //data.items[0].statistics does give me the object that I want
      vid['statistics'] = data.items[0].statistics
    })
    
    this.setState({ videos: data.items });
    console.log(this.state.videos);
  }




基本上,上述onSearch方法会调用YouTube API并在data.items

中返回一个视频列表

对于每个video/item,它们都缺少statistics,所以我发出另一个调用来检索数据,数据成功返回data.items[0].statistics,我是然后考虑作为财产追加到个别项目中。

没有抛出异常,但我也没有看到新创建的statistics属性。这个想法就像下面的一个非常简单的形式。



let items = [
  {id: '123', title: 'John'},
  {id: '123', title:'sammy'}
]

items.forEach(x=> {
	x['statistics'] = { propA: 'A', propB: 'B'};
})

console.log(items);




1 个答案:

答案 0 :(得分:2)

async中放置forEach函数将不会暂停外部线程,直到所有迭代完成为止 - 每次异步迭代需要Promise.allmap Promise并等待每个Promise解决,然后继续:

const query = qs.stringify({ ...API_QUERY_PARAMS, q: this.state.searchString });
const url = `https://www.googleapis.com/youtube/v3/search?${query}`

const { data } = await axios.get(url);

await Promise.all(data.items.map(async (vid) => {
  let id = vid.id.videoId; //Individual video ID
  const individualQuery = qs.stringify({ ...INDIVIDUAL_API_QUERY_PARAMS, id  });
  const individualURL = `https://www.googleapis.com/youtube/v3/videos?${individualQuery}`;
  const { data } = await axios.get(individualURL);
  vid.statistics = data.items[0].statistics
}))

this.setState({ videos: data.items });