javascript - 用于使用游标对 api 进行分页的 Axios 递归

标签 javascript node.js recursion axios

如何使用 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/

相关文章:

javascript - 如何使用cheerio和nodejs在解析的HTML中查找特定的JavaScript代码?

java - 逃离有时间限制的递归

javascript - 具有 Node.js 异步的 API 数据并检索数据使其同步

javascript - 设置 slider Bootstrap 值

javascript - react native : Can't style the Button

php - 在environment.prod.ts 文件上设置条件

node.js - 保持 Node JS 应用程序运行

javascript - 客户端模板引擎 (Rivets.js) 中的性能渲染缓慢

python - 使递归函数迭代?

algorithm - 是否可以将所有递归函数重写为尾递归?