如何使用未知数量的令牌的承诺?

时间:2017-05-31 21:35:58

标签: javascript node.js promise

以下代码从YouTube视频的评论部分检索评论。问题是它检索了20条评论,如果还有更多则会检索下一条标记。我对使用promises的经验不是很充实,所以我想知道如果没有任何令牌,我怎样才能获得该部分的所有评论?

此代码是名为youtube-comment-api

的npm包中的示例代码

我想我的问题很容易解决,但现在我没有任何线索。

示例:

const fetchCommentPage = require('youtube-comment-api')
const videoId = 'DLzxrzFCyOs'



fetchCommentPage(videoId)
  .then(commentPage => {
    console.log(commentPage.comments)

    return fetchCommentPage(videoId, commentPage.nextPageToken)
  })
  .then(commentPage => {
    console.log(commentPage.comments)
  })

1 个答案:

答案 0 :(得分:2)

您应该使用递归来获取所有页面的评论。这样的事情应该有效:

// returns a list with all comments
function fetchAllComments(videoId, nextPageToken) {
  // nextPageToken can be undefined for the first iteration
  return fetchCommentPage(videoId, nextPageToken)
   .then(commentPage => {
    if (!commentPage.nextPageToken) {
        return commentPage.comments;
    }
    return fetchAllComments(videoId, commentPage.nextPageToken).then(comments => {
      return commentPage.comments.concat(comments);
    });
  });
}
相关问题