yodog
yodog

Reputation: 6242

how can i fetch paginated json data with a recursive function

i need some help turning the function below into a recursive function.
it should call itself until a specific http header is not present anymore, then execute the last two functions fncParse() and fncDrawTbl.
i'm getting the error recfnc is not a function.

// use gitlab api to fetch json data
// must check response http headers to iterate over all pages
// recursively call the function while there is a 'rel="next"' link header

var filteredJsonData = [];
var parsedJsonData   = [];

recfnc = function() {
    var req = $.getJSON(url, function(jsondata) {
        var hdrlink, linknext, relnext;

        filteredJsonData.push(fncFilter(jsondata));

        try {
            hdrlink  = req.getResponseHeader('link').split(',');
            relnext  = hdrlink.filter(l => l.toLowerCase().indexOf('rel="next"') > -1);
            linknext = relnext[0].split('<')[1].split('>')[0];
        }
        catch (e) { console.log(e); }

        if (linknext) {
            recfnc(linknext);
        }
        else {
            parsedJsonData.push(fncParse(filteredJsonData));
            fncDrawTbl(['Name', 'Issues', 'Hours'], parsedJsonData, '#contentKPI');
        }
    });
}(url);

Upvotes: 0

Views: 109

Answers (1)

Ivan V.
Ivan V.

Reputation: 8091

The reason that your function doesn't work assuming that recfnc = is just an error in your question not in the original code (it should be const recfnc=)

What you are actually storing in the recfnc variable is a result of the function call fn(){}(url) not the function itself. In your case, recfnc variable actually holds undefined value.

Change this:

recfnc = function(){}

// to:

(function recfnc(){}(url))

Upvotes: 2

Related Questions