data returned by YouTube API seems immutable?

2019-07-26 22:20发布

问题:

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

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

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.

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

回答1:

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