如何使用 axios
对带有游标的 API 进行分页?我想递归调用此函数直到 response.data.length < 1
并在完成后返回包含集合中所有项目的整个数组。另外,值得注意的是,我必须将光标传递到后续调用中。
function getUsers () {
return axios.get('/users') // API supports a cursor param (?after=)
.then(response => {
// returns an array with a cursor
// see response below
console.log(response.data)
})
}
示例响应:
{
"total": 100,
"data": [
{
user: "Bob"
},
{
user: "Sue"
},
{
user: "Mary"
},
],
"pagination": {
"cursor": "lkdjsfkljsdkljfklsdjfkjsdk"
}
}
提前感谢您的帮助。
最佳答案
这是一个递归函数,用于管理响应中的游标:
function getUsers (cursor, data = []) {
return axios.get('/users' + (cursor ? '?after='+cursor : '')) // API supports a cursor param (?after=)
.then(response => {
if (response.data.length < 1 ) return data
data.push(...response.data)
return getUsers(response.pagination.cursor, data)
})
}
// use it to get data
getUsers()
.then(data => console.log("final data", data))
这就是它如何使用伪造的 axios
函数和一些额外的日志记录来显示顺序:
// Fake axios get -- just return numbers so it's easy to test
let axios = {
data: data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
get(url) {
let cursor = parseInt(url.split('?after=')[1] || 0)
console.log("cursor:", cursor)
let ret_data = data.slice(cursor, cursor +5)
return new Promise(resolve => setTimeout(() => resolve({
"total": 15,
"data": ret_data,
"pagination": {
"cursor": cursor +5
}
}), 400)
)
}
}
function getUsers (cursor, data = []) {
return axios.get('/users' + (cursor ? '?after='+cursor : '')) // API supports a cursor param (?after=)
.then(response => {
console.log("getting data", response.data)
if (response.data.length < 1 ) return data
data.push(...response.data)
return getUsers(response.pagination.cursor, data)
})
}
getUsers()
.then(data => console.log("final data", data))
关于javascript - 用于使用游标对 api 进行分页的 Axios 递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51510699/