YouTube API返回的数据似乎是一成不变的? [英] data returned by YouTube API seems immutable?

查看:50
本文介绍了YouTube API返回的数据似乎是一成不变的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 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

Basically the above onSearch method will call YouTube API and return me a list of videos, in data.items

对于每个video/item,它们都缺少statistics,因此我要触发另一个调用以检索数据,数据成功返回为data.items[0].statistics,我当时想将其追加到单个项中,如下所示:财产.

For each and every video/item, they are lacking of statistics and so I'm firing another call to retrieve the data, the data successfully returned as data.items[0].statistics, I was thinking then to append into individual item as a property.

没有引发异常,但是我也看不到新创建的statistics属性.这个想法如下所示,非常简单.

No exception being thrown, however I don't see the newly created statistics property too. The idea is like below in a very much simpler form.

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

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

console.log(items);

推荐答案

在所有迭代均已完成之前将async函数放入forEach不会暂停外线程-您需要Promise.all将每个异步迭代复制到Promise,并等待每个Promise得到解决,然后再继续:

Putting an async function inside a forEach won't pause the outer thread until all iterations have been completed - you need Promise.all to map each asynchronous iteration to a Promise and wait for each Promise to be resolved before continuing instead:

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 });

这篇关于YouTube API返回的数据似乎是一成不变的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆