2017-05-31 32 views
0

以下代碼將從YouTube視頻的評論部分中檢索評論。事情是它檢索20條評論,如果有更多,它檢索下一個標記。我沒有很有經驗的使用承諾,所以我不知道如何才能在該部分獲得所有評論,直到沒有任何標記了?如何使用具有未知數量的令牌的承諾?

此代碼是從NPM包的示例代碼,名爲youtube-comment-api

我想我的問題是很容易解決,但現在我不知道。


例子:

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) 
    }) 
+0

該代碼看起來應該工作。怎麼了? – James

回答

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

正確的想法,但你的方法有一個小錯誤 - 除了缺少一個返回聲明,我糾正了。您在最後一個'then>中無法訪問'commentPage.comments'。也許你打算編寫'return fetchAllComments(...)。然後(comments => commentPage.comments.concat(comments))''。 – royhowie

+0

謝謝。我現在解決了。 – amiramw

+0

謝謝,明天我會試試看。 –