在不知道页码的情况下获取分页数据

Fetch paginated data without knowing the page number

我有一个 API 只允许获取 1000 rows/fetch。

因此,例如,如果我想从 API 检索所有数据,我的想法是在每次获取响应数据时循环遍历并检查它的 length(如果 responseData.length !== 0,然后继续取,当responseData.length === 0时停止,同样每次开始新的循环时增加firstRow,直到到达结束(responseData.length === 0)

const fetchDataByRowCount = async (url, token, rowCount = 2, firstRow = 0) => {
// firstRow is the value where the next fetch starts (E.g: 0-999, 1000-1999, etc.).
// rowCount is the value for total rows fetched (E.g: 1000 rows for each fetching time).
  const data = await axios({
    method: "get",
    url: `${url}?rowCount=${rowCount}&firstRow=${firstRow}`,
    headers: {
      client_id: "",
      Authorization: `Bearer ${token}`,
    },
  });
  return data.data;
};
export const paginatedFetch = async (url, type, rowCount = 2, firstRow = 0) => {
  let newResponse;
  let total = [];
  let token = await getToken(type); // stored to reuse token within an hour
  do {
    if (!token) {
      const newToken = await getToken(type);
      newResponse = await fetchDataByRowCount(url, newToken);
    } else {
      newResponse = await fetchDataByRowCount(
        url,
        token,
        (rowCount = 2),
        (firstRow = 0)
      );
    }
    // console.log(total, "total");
    total = [...total, ...newResponse];
    // newResponse = [];
    let newFirstRow = firstRow + 1000;

    newResponse = await fetchDataByRowCount(
      url,
      token,
      (rowCount = 2),
      newFirstRow
    );
    total = [...total, ...newResponse];
  } while (newResponse.length !== 0);
  return total;
};

但问题是我的函数没有退出do while循环,newResponse总是returns值!==0。 另外,该函数只运行一次。

你们能帮我检查一下吗?

从您发布的代码来看,还有一点我无法弄清楚,那就是rowCount,所以我在下面的“重制”代码中照原样:

export const paginatedFetch = async (url, type, rowCount = 2, firstRow = 0) => {
  let newResponse;
  let total = [];
  let token;
  let numberOfRows = firstRow;
  do {
    if (!token) token = await getToken(type);

    newResponse = await fetchDataByRowCount(
      url,
      token,
      (rowCount = 2),
      numberOfRows
    );
    total = [...total, ...newResponse];
    numberOfRows += 1000;
  } while (newResponse.length !== 0);
  return total;
};

我去掉了一些多余的东西,并通过变量赋值等使代码更高效

你也提到这个:

the newResponse always returns value !==0.

这样做要小心,因为 newResponse 最初是 undefined。现在我从未使用过 do...while 循环,所以我不知道 确切地 会发生什么,但是它可能根本 运行 都不会。因此 Also, the function only runs once 如果你在谈论 paginatedFetch 函数。

现在如果我要 re-write 它,我会这样做:

export const paginatedFetch = async (url, type, rowCount = 2, firstRow = 0) => {
  let total = [];
  let token;
  let numberOfRows = firstRow;
  while (true) {
    if (!token) token = await getToken(type);
    let res = await fetchDataByRowCount(
      url,
      token,
      (rowCount = 2),
      numberOfRows
    );
    total = [...total, ...res];
    numberOfRows += 1000;
    if (res.length <= 0) break;
  }
  return total;
};

再说一次,小心 while (true),你必须绝对 确定 API returns 和 res 确实是一个array.

更好的解决方案是 API(如果您是开发人员)提供一个端点来计算总行数。这样,您将有办法绝对确定有多少行并围绕它编写代码。