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