Javascript 如何将承诺与未知数量的代币一起使用?
下面的代码从youtube视频的评论部分检索评论。问题是它检索20条注释,如果有更多注释,则检索下一个标记。我对使用承诺不是很有经验,所以我想知道在没有代币之前,我如何才能获得该部分中的所有评论 此代码是一个名为 我想我的问题很容易解决,但现在我没有线索Javascript 如何将承诺与未知数量的代币一起使用?,javascript,node.js,promise,Javascript,Node.js,Promise,下面的代码从youtube视频的评论部分检索评论。问题是它检索20条注释,如果有更多注释,则检索下一个标记。我对使用承诺不是很有经验,所以我想知道在没有代币之前,我如何才能获得该部分中的所有评论 此代码是一个名为 我想我的问题很容易解决,但现在我没有线索 示例: const fetchCommentPage = require('youtube-comment-api') const videoId = 'DLzxrzFCyOs' fetchCommentPage(videoId)
示例:
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)
})
您应该使用递归从所有页面获取注释。像这样的方法应该会奏效:
// 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);
});
});
}
您应该使用递归从所有页面获取注释。像这样的方法应该会奏效:
// 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);
});
});
}
该代码看起来应该可以工作。发生了什么?那代码看起来应该能用。发生了什么?好主意,但是除了缺少返回语句之外,您的方法还有一个小错误,我已经纠正了。您没有访问
commentPage的权限。在最后一个then
中添加了注释。也许你想写返回fetchAllComments(…)。然后(comments=>commentPage.comments.concat(comments))
。谢谢。我现在已经修好了。谢谢,我明天会试试。效果很好,但我认为它很难阅读,所以它不会让我喜欢承诺,但我认为这是我个人的问题:)好主意,但你的方法中有一个小错误,除了缺少回报声明之外,我已经纠正了。您没有访问commentPage的权限。在最后一个then
中添加了注释。也许你想写返回fetchAllComments(…)。然后(comments=>commentPage.comments.concat(comments))
。谢谢。我现在已经修好了。谢谢,我明天会试试。效果很好,但我认为它很难阅读,所以它不会让我喜欢承诺,但我认为这是我个人的问题:)