我碰到一个可以给我用户列表的端点,但是结果是分页的。响应包含一个标志hasMore
,该标志指示是否还有更多用户要检索,另外一个标志offset
用于进行下一个api调用。
现在,我可以通过手动检查结果hasMore
是否为真来进行多个呼叫。如何在while循环中包装此逻辑?
function getUsers() {
let users = [];
axios.get(url)
.then(res => {
res.users.forEach(user => {
users.push(user);
})
if (res.hasMore) {
return axios.get(url + '&offset=' + res.offset)
}
})
.then(res => // repeat what I've just done and keep checking hasMore
// How do I check this in a while?
}
答案 0 :(得分:2)
您可以将users = []
向上移动一个水平吗?
let users = [];
function getUsers(url) {
axios
.get(url)
.then(res => {
res.users.forEach(user => {
users.push(user);
})
if (res.hasMore) {
getUsers(url + '&offset=' + res.offset);
}
})
.catch(err => {...});
}