我想用承諾調用分頁API。有多少頁面可用的信息在開始時是未知的,但會在每個響應中傳遞。在細節我打電話一吉拉search,尋呼信息的部分看起來像:用承諾調用分頁API
{
"startAt": 0,
"maxResults": 15,
"total": 100000,
...
}
我解決了遞歸分頁的處理,這是我在打字稿的解決方案:
search(jql: string, fields: string[] = [], maxResults = 15) : Promise<JiraIssue[]> {
// container for the issues
let issues: Array<JiraIssue> = new Array<JiraIssue>();
// define recursive function to collect the issues per page and
// perform a recursive call to fetch the next page
let recursiveFn = (jql: string, fields: string[], startAt: number, maxResults: number) :
Promise<JiraIssue[]> => {
return this
// retrieves one page
.searchPage(jql, fields, startAt, maxResults)
.then((searchResult: JiraSearchResult) => {
// saves the result of the retrieved page
issues.push.apply(issues, searchResult.issues);
if (searchResult.startAt + searchResult.maxResults < searchResult.total) {
// retrieves the next page with a recursive call
return recursiveFn(jql, fields,
searchResult.startAt + searchResult.maxResults,
maxResults);
}
else {
// returns the collected issues
return issues;
}
})
};
// and execute it
return recursiveFn(jql, fields, 0, maxResults);
}
然而,我不喜歡遞歸方法,因爲這隻適用於小結果集(我害怕堆棧溢出)。如何用非遞歸方法解決這個問題?
這不是實際的遞歸,並且沒有堆棧溢出的危險,因爲函數在一個then中被調用。 – 2016-05-16 14:24:29