Wednesday, 12 April 2017

Promise looping over nested arrays

I'm wrestling with nested promise loops and having trouble finding a working solution.

I looked around and found this: http://stackoverflow.com/a/29396005/3560729

The promiseWhile function seems to have what I need but I'm having trouble getting the nesting to return to the outer loop

promiseWhile:

function promiseWhile(predicate, action) {
    function loop() {
    if (!predicate()) return;
        return Promise.resolve(action()).then(loop);
    }
    return Promise.resolve().then(loop);
}

Nested Loop:

    let outerArray = outerArrayOfObjects;
    let returnArray = [];
    let returnArrayIndex = 0;
    let outerIndex = 0;
    let outerLength = outerArray.length;
    let passObject = { }; 

    promiseWhile(function() {
        return outerIndex < outerLength;
    }, function() {
        let innerIndex = 0;
        let innerLength = outerArray[outerIndex].innerArray.length;

        passObject = {
            innerObject: outerArray[outerIndex].innerArray[innerIndex],
            returnArray: returnArray,
            returnArrayIndex: returnArrayIndex
        };
        promiseWhile(function() {
            return innerIndex < innerLength;
        }, function() {
            return new Promise(function(resolve, reject){
                Promise.all([
                    promiseFunction1(innerObject),
                    promiseFunction2(innerObject),
                    promiseFunction3(innerObject),
                ])
                    .then(function (allMappings) {
                        passObject.returnArray[returnArrayIndex++] = {
                            "result1": allMappings[0],
                            "result2": allMappings[1],
                            "result3": allMappings[2]
                        }
                        offersIndex++;
                        return resolve(passObject)
                    })
                    .catch(function (err) {
                        offersIndex++;
                        return reject(err);
                    })
            })
        })
        outerIndex++;
    }).then(function() {
        return resolve(passObject);
    });
  })
}

I think my main questions are: Where do I process the results? How should I pass the values such that the return array is built properly?



via GForce

No comments:

Post a Comment