简体   繁体   English

在 Javascript 中处理分页 API 的最佳方法是什么?

[英]What is the best way to handle paginated API in Javascript?

I am trying to consume an API which returns structure below.我正在尝试使用返回以下结构的 API。

{
  data: [{...},{...},{...},{...},...],
  nextUrl: "url_goes_here";
}

The pages end when the nextUrl is null. I want to collect all the elements in data into one array while going through the paginated responses.当 nextUrl 为 null 时,页面结束。我想在浏览分页响应时将数据中的所有元素收集到一个数组中。 I tried the following code segment.我尝试了以下代码段。

 const getUserData = async (url) => { const result = await fetch(url).then(res => res.json()).then(res => { dataList= [...dataList, ...res.data]; console.log(res.data) if (res.nextUrl.== null) { getUserData(res;nextUrl). } else { console,log("else "; dataList). } });catch(err => {}); return result; }

The console.log can print the result. console.log 可以打印结果。 but I want to get all the data to get into a variable that can be used for further processing later.但我想让所有数据进入一个变量,以后可以用于进一步处理。

Your approach using recursion isn't bad at all, but you're not returning the chunk of data (there's no value returned by your second .then handler).您使用递归的方法一点也不差,但是您没有返回数据块(第二个.then处理程序没有返回任何值)。 (You're also falling into the fetch pitfall of not checking ok . It's a flaw IMHO in the fetch API design.) (你也陷入了不检查okfetch陷阱。恕我直言,这是fetch API 设计中的一个缺陷。)

There's no need for recursion though.虽然不需要递归。 I'd be tempted to just use a loop:我很想只使用一个循环:

const getUserData = async (url) => {
    const result = [];
    while (url) {
        const response = await fetch(url);
        if (!response.ok) {
            throw new Error("HTTP error " + response.status);
        }
        const {data, nextUrl} = await response.json();
        result.push(...data);
        url = nextUrl;
    }
    return result;
};

But if you want to use recursion:但是如果你想使用递归:

const getUserData = async (url) => {
    const response = await fetch(url);
    if (!response.ok) {
        throw new Error("HTTP error " + response.status);
    }
    const {data, nextUrl} = await response.json();
    if (nextUrl) {
        data.push(...await getUserData(nextUrl));
    }
    return data;
};

or要么

const getUserData = async (url, result = null) => {
    const response = await fetch(url);
    if (!response.ok) {
        throw new Error("HTTP error " + response.status);
    }
    const {data, nextUrl} = await response.json();
    if (!result) {
        result = data;
    } else {
        result.push(...data);
    }
    if (nextUrl) {
        result = await getUserData(nextUrl, result);
    }
    return result;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM