JSFiddle - React, Tailwind, and code Playground

by jfriend00

JavaScript

let conditions = 0;

function runMatchIteration(data, offset, limit) {
    let i = offset;
    let entities = [];
    
    function next() {
        if (i < data.length && entities.length < limit) {
            return readEntity(data[i++]).then(instance => {
                return matchInstance(instance, conditions).then(isMatch => {
                    if (isMatch) {
                        entities.push(instance);
                    }
                    // now execute next cycle - chaining onto original promise
                    return next();
                });
            });
            
        } else {
            // done with loop here
            return entities;
        }
    }
    
    return Promise.resolve().then(next);
}

function readEntity(val) {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve(val);
        }, Math.floor(Math.random() * 50));
    });
}

function matchInstance(instance, conditions) {
    return new Promise(resolve => {
        setTimeout(() => {
            // make a 2/3 chance of resolving true
            resolve(Math.random() > 0.33);
        }, Math.floor(Math.random() * 50));
    });
}

let d = [1,2,3,4,5,6,7,8,9];

runMatchIteration(d, 0, 5).then(result => {
    console.log(result);
});