I'm currently learning NodeJS, promises, and recursion. I'm trying to make a function that fetches videos from a YouTube Channel using the YouTube Data API.
The thing is, the max results it will return is 50 at once. You can solve this by using a pageToken, which is obtained with the request if the results are larger than 50.
I'm trying to use recursion to fetch all data using pageTokens, however I don't see any results using the function. It doesn't return anything:
let getVideos = (id, token=null, data=[]) => {
return new Promise((resolve, reject) => {
axios.get('https://www.googleapis.com/youtube/v3/search', {
params: {
key: config.youtubeApiKey,
part: 'snippet',
channelId: id,
maxResults: 50,
pageToken: token
}
}).then((response) => {
if (response.data.pageInfo.totalResults === 0) {
reject("No videos found for this Channel ID.");
}
data.push(response.data.items);
if (!response.data.nextPageToken) {
return resolve(data);
}
return getVideos(id, response.data.nextPageToken, data);
}).catch((e) => {
if (e.code === 'ENOTFOUND') {
reject("Unable to connect to the YouTube API");
} else {
reject(e.message);
}
});
});
};
via reinierkors
No comments:
Post a Comment