我想使用 Promise 调用分页 API。有多少页可用的信息一开始并不知道,但会在每次响应时传递。详细来说我正在调用Jira search ,分页信息部分如下所示:
{
"startAt": 0,
"maxResults": 15,
"total": 100000,
...
}
我用递归解决了分页的处理,这是我在 Typescript 中的解决方案:
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
处理程序内调用的。
关于javascript - 使用 Promise 调用分页 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37252673/