Axios递归用于使用游标分页api

Tec*_*Tim 6 javascript recursion cursor node.js axios

如何使用游标对API进行分页axios?我想以递归方式调用此函数,直到完成后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)
             })
}
Run Code Online (Sandbox Code Playgroud)

响应示例:

{
    "total": 100,
    "data": [
        {
            user: "Bob"
        },
        {
            user: "Sue"
        },
        {
            user: "Mary"
        },
    ],
    "pagination": {
        "cursor": "lkdjsfkljsdkljfklsdjfkjsdk"
    }
}
Run Code Online (Sandbox Code Playgroud)

提前谢谢你的帮助.

Mar*_*yer 14

这是一个递归函数,用于管理响应中的游标:

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))
Run Code Online (Sandbox Code Playgroud)

这是如何使用伪造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))
Run Code Online (Sandbox Code Playgroud)

  • 这次真是万分感谢。这似乎需要一些修改,主要是围绕“axios”的工作方式和 API 的形状。`data.push(...response.data.data)` `return getUsers(response.data.pagination.cursor, data)` (2认同)