2
function reduce(functn, intialPromise) {
    var proceed = true;
    var promise = intialPromise;
    do {
        functn(promise).then(next => {
            proceed = next.proceed;
            promise = next.promise;
        });
    } while(proceed);
    return promise;
}

Worker function

let promiseFunction = (promise) => {
    let proceed = true;
    return promise.then(() => {

        // some processing in which proceed can become false

        let nextPromise = {};
        if(proceed){
            nextPromise.proceed = true;
            nextPromise.promise = next promise task;
        }
        else {
            nextPromise.proceed = false;
            nextPromise.promise = Promise.resolve(true);
        }
        return Promise.resolve(nextPromise);
    });
};

Execution

reduce(promiseFunction, initialPromise).then(() => {
    return success;
});

This code is looping continuously.

The idea was to have chained promise. The data on which promise acts is big say 1 GB. but the allocated memory for promise processing is low - 100 MB. So the promise has to run in chain - taking small batches which fit into memory.

Also currently tied to ES6 code, and polyfills/transpiling is not added yet. Hence expecting result in ES6 code.

PS: Not a javascript expert, kindly apologise for blunders

James Z
  • 12,209
  • 10
  • 24
  • 44
binoyees
  • 53
  • 8
  • what are you providing in place of `initialPromise` ? – Prasanna Oct 13 '17 at 10:47
  • Its a valid promise - assume its `Promise.resolve(true)` – binoyees Oct 13 '17 at 11:02
  • `then` returns a promise without executing the handlers supplied in call. These are executed asynchronously, some time later, if and when the promise `then` was called on is settled. The code that changes `proceed` is asynchronous, executed later, and does not change the loop variable while the loop is executing - so it loops forever. Try searching for "recursive promise function" (543 results on SO) – traktor Oct 13 '17 at 12:22
  • https://stackoverflow.com/questions/17217736/while-loop-with-promises, https://stackoverflow.com/q/24660096/1048572 – Bergi Oct 13 '17 at 12:45

2 Answers2

0

Just a quick look at this:

At no point do you set "proceed" to "false", so it will continue to loop your do-while.

cmprogram
  • 1,854
  • 2
  • 13
  • 25
0

The problem is do-while is synchronous (if I'm right). Have a look at JavaScript ES6 promise for loop

With async/await it should work

async function reduce(functn, intialPromise) {
    var proceed = true;
    var promise = intialPromise;
    do {
        const result = await functn(promise);
        proceed = result.proceed;
        promise = result.promise;
    } while(proceed);
    return promise;
}
Tobias Timm
  • 1,855
  • 15
  • 27
  • Thanks @tobias-timm answer in the above link solves the problem. https://stackoverflow.com/a/40329190/7348879 – binoyees Oct 13 '17 at 13:16