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

答案 0 :(得分:2)
在async
中放置forEach
函数将不会暂停外部线程,直到所有迭代完成为止 - 每次异步迭代需要Promise.all
到map
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 });