Amit
Amit

Reputation: 53

Recursively calling a promise function

How will i write a promise function that recursively calls itself? What i ended up is like the one below.

function myPromiseFunction(input) {
    return new Promise(function(resolve, reject) {
        //compute something with input and got new input so again calling
        //myPromiseFunction
        if (newInput) {
            return myPromiseFunction(new input);
        }
        else {
            resolve(output);
        }
    });
}
myPromiseFunction(input).then(function(output) {
    console.log("completed processing data with input" );
});

Nothing is logged when i run the code. What am i doing wrong here?

Upvotes: 2

Views: 120

Answers (2)

user663031
user663031

Reputation:

I'm assuming that "compute something with input" is the asynchronous part of this flow, and that it returns a promise resolving to [output, newInput]. Please correct me if this assumption is wrong.

You don't need a constructor at all. Rather than constructing promise after promise and then resolving it with the results of other promises, you can simply say:

function getOutput(input) {
  return computeSomething(input) .
    then(([output, newInput]) => newInput ? getOutput(newInput) : output);
}

Upvotes: 0

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276266

Don't use explicit construction.

If you have to use it, resolve assimilates promises passed into it:

function myPromiseFunction(input) {
    return new Promise(function(resolve, reject) {
        //compute something with input and got new input so again calling
        //myPromiseFunction
        if (newInput) {
            resolve(myPromiseFunction(newInput)); // will wait for inner promise
        }
        else {
            resolve(output);
        }
    });
}

Quoting the specification:

The resolve function that is passed to an executor function accepts a single argument. The executor code may eventually call the resolve function to indicate that it wishes to resolve the associated Promise object. The argument passed to the resolve function represents the eventual value of the deferred action and can be either the actual fulfillment value or another Promise object which will provide the value if it is fulfilled.

Upvotes: 3

Related Questions