jsanjayce
jsanjayce

Reputation: 352

Javascript - Return Promise at the end of recursion function with delay

I am very new to javascript and trying to create a recursion function in Javascript which should return a promise at the end of the recursion. But, with the below code snippet, I am getting the promise returned on the single iteration.

function delayedIteration(i) {
    var promises = [];
    var promise = new Promise(function(resolve, reject) {
        if(i >= 10) {
            return;
        }
        console.log("i: "+i);
        i++;
        setTimeout(delayedIteration.bind({}, i), 3000);
        resolve("resolve");
    });
    promises.push(promise);
    return Promise.all(promises);
}

I also tried adding,

setTimeout(promises.push(delayedIteration.bind({}, i)), 3000);

But, it doesn't help either. Could someone please help me with this.

Upvotes: 1

Views: 653

Answers (2)

Patrick Hund
Patrick Hund

Reputation: 20236

You can chain the promises returned by the recursive function calls using their then methods, like this:

function delayedIteration(max, i = max + 1) {
    return new Promise(resolve => {
        if (i === 1) {
            resolve();
            return;
        }
        delayedIteration(max, --i).then(() =>
            setTimeout(() => {
                console.log(i);
                resolve();
            }, 3000)
        );
    })
}
delayedIteration(10);

Note that I'm counting from the max to 1 here, because the promises that are at the end of the chained then statements are resolved first (there's probably lots of possibilities to optimize this code 😀)

See JSFiddle: https://jsfiddle.net/pahund/q4cuwse9/

Upvotes: 1

Evert
Evert

Reputation: 99543

Promises return immediately but resolve later. A promise basically encapsulates a 'future result' to a function.

Upvotes: 0

Related Questions