最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Youtube API with JavaScript - Show all videos from a playlist - Stack Overflow

programmeradmin2浏览0评论

I'm trying to get all 137 videos from a Youtube playlist with the following code:

function loadVideos() {

  let pagetoken = '';
  let resultCount = 0;
  const mykey = "***********************************";
  const playListID = "PLzMXToX8Kzqggrhr-v0aWQA2g8pzWLBrR";

  const URL =  `?
part=snippet
&maxResults=50
&playlistId=${playListID}
&key=${mykey}`;


  fetch(URL)
    .then(response => {
      return response.json();
    })
    .then(function(response) {

      resultCount = response.pageInfo.totalResults;
      console.log("ResultCount: " + resultCount);

      pagetoken = response.nextPageToken;
      console.log("PageToken: " + pagetoken);

      resultCount = resultCount - 50;
      console.log("ResultCount: " + resultCount);

      while (resultCount > 0) {

        const URL = `?
part=snippet
&maxResults=50
&playlistId=${playListID}
&key=${mykey}
&pageToken=${pagetoken}`;

        fetch(URL)
          .then(response => {
            return response.json();
          })
          .then(function(response) {
            pagetoken = response.nextPageToken ? response.nextPageToken : null;
            console.log("PageToken: " + pagetoken);
          });
        resultCount = resultCount - 50;
      }
    })
    .catch(function(error) {
      console.log("Looks like there was a problem: \n", error);
    });
} // End of loadVideos function

// Invoking the loadVideos function
loadVideos();

The first 50 videos get loaded The second 50 videos get loaded too But instead of loading the remaining 37 videos from the list, my script loads the previous 50 videos again.

It seems that the pagetoken doesn't get updated for the third request.

What is wrong with my code?

I'm trying to get all 137 videos from a Youtube playlist with the following code:

function loadVideos() {

  let pagetoken = '';
  let resultCount = 0;
  const mykey = "***********************************";
  const playListID = "PLzMXToX8Kzqggrhr-v0aWQA2g8pzWLBrR";

  const URL =  `https://www.googleapis./youtube/v3/playlistItems?
part=snippet
&maxResults=50
&playlistId=${playListID}
&key=${mykey}`;


  fetch(URL)
    .then(response => {
      return response.json();
    })
    .then(function(response) {

      resultCount = response.pageInfo.totalResults;
      console.log("ResultCount: " + resultCount);

      pagetoken = response.nextPageToken;
      console.log("PageToken: " + pagetoken);

      resultCount = resultCount - 50;
      console.log("ResultCount: " + resultCount);

      while (resultCount > 0) {

        const URL = `https://www.googleapis./youtube/v3/playlistItems?
part=snippet
&maxResults=50
&playlistId=${playListID}
&key=${mykey}
&pageToken=${pagetoken}`;

        fetch(URL)
          .then(response => {
            return response.json();
          })
          .then(function(response) {
            pagetoken = response.nextPageToken ? response.nextPageToken : null;
            console.log("PageToken: " + pagetoken);
          });
        resultCount = resultCount - 50;
      }
    })
    .catch(function(error) {
      console.log("Looks like there was a problem: \n", error);
    });
} // End of loadVideos function

// Invoking the loadVideos function
loadVideos();

The first 50 videos get loaded The second 50 videos get loaded too But instead of loading the remaining 37 videos from the list, my script loads the previous 50 videos again.

It seems that the pagetoken doesn't get updated for the third request.

What is wrong with my code?

Share edited Apr 4 at 10:09 VLAZ 29.2k9 gold badges63 silver badges84 bronze badges asked Oct 25, 2018 at 13:32 user1941537user1941537 6,70517 gold badges68 silver badges114 bronze badges 1
  • I'm still struggling to find a solution for this. Any help would be appreciated. – user1941537 Commented Oct 27, 2018 at 10:13
Add a ment  | 

3 Answers 3

Reset to default 6

You don't need to make a Math with 50 - maxResults, just lookup for nextPageToken and make the code recall the api if there is a new token.

For Example

function getUrl(pagetoken) {
  var pt = (typeof pagetoken === "undefined") ? "" :`&pageToken=${pagetoken}`,
      mykey = "************",
      playListID = "PLzMXToX8Kzqggrhr-v0aWQA2g8pzWLBrR",
      URL = `https://www.googleapis./youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=${playListID}&key=${mykey}${pt}`;
  return URL;
}


function apiCall(npt) {
  fetch(getUrl(npt))
  .then(response => {
      return response.json();
  })
  .then(function(response) {
      if(response.error){
        console.log(response.error)
      } else {
        responseHandler(response)
      }

  });
}

function responseHandler(response){
  if(response.nextPageToken)
    apiCall(response.nextPageToken);

  console.log(response)
}
apiCall();

If you see the api makes 3 calls because after the third there is no nextPageToken

You're looping through asynchronous functions without waiting for a response. Try adding async in front of your function declaration and await in front of your fetch...

function loadVideos() {
// ...

    .then(async function(response) {
    // ...

        while (resultCount > 0) {
        // ...

            await fetch(URL)
                .then(response => {
                // ...

Or if your setup doesn't support async/await, use bluebird's Promise.mapSeries with an empty array of length = resultCount, something like this

kindly i sugest you to remove your API KEY from the code and simply put the other signs or let it be blank for understandings for others.

发布评论

评论列表(0)

  1. 暂无评论