JSFiddle - React, Tailwind, and code Playground

JavaScript

function make_next(api, initial) {
    return function(data, status, xhr) {
        if(xhr && xhr.status >= 400) {
            return false;
        }
        if(initial > 2) {
            return true;
        }
        if (arguments.length != 0) {
            initial += 1;
        }
        return $.get(api, { p: initial });
    };
}

function make_fold() {
    var accumulated = []
    return function(data, status, xhr) {
        if(data) 
            accumulated.push(data);
        return accumulated;
    }
}

function poll_general(next, fold, this_arg) {
    var deferred = $.Deferred();
    function polling() {
        // Now we resolve/reject deferred per next()
        var iteration = next.apply(this_arg, arguments);
        if(iteration && iteration.then) {
            fold.apply(null, arguments);
            return iteration.then(polling);
        } else if (iteration) {
            deferred.resolve(fold());
        } else {
            deferred.reject(fold());
        }
        return deferred.promise();
    }
    return next().then(polling);
}

poll_general(make_next('http://fiddle.jshell.net',0), make_fold())
.then(function(accumulated){
    console.log(accumulated);
});