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

最佳答案

在所有迭代完成之前,将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 });

10-08 18:33