0

I have a function which has nested Promises within it. I want to re-execute this function when there is a length value of streamRes.length. Currently, it only executes the code and prints out the length on the console but doesn't re-execute.

let fetchEnrolleesData = () => {
    getLastUpdatedEnrollee().then(res => {
        let params = path+"enrollees?limit=100";
        params += res.last_date ? "&last_updated_at=" + res.last_date.value : '';

        fetchEnrolleesDataInStream(res, params).then(streamRes => {
            if(streamRes.length) {
                console.log(streamRes.length);
                fetchEnrolleesData();
            }
        });
    });
}
James Z
  • 12,209
  • 10
  • 24
  • 44
  • 5
    You're not returning the promise returned by `getLastUpdatedEnrollee`, nor the promise `getLastUpdatedEnrollee`. – evolutionxbox Jul 19 '20 at 17:34
  • Related: https://stackoverflow.com/questions/29020722/recursive-promise-in-javascript – ericArbour Jul 19 '20 at 17:37
  • 2
    *"but doesn't re-execute."*: yes it does (even if you did not return the promises), but without knowing about the other functions in your code, and how you use the main call of this function, we cannot really say why it does not behave as you expect it to. Put some more `console.log` calls in your code to see for instance when the `length` is 0, when it executes any of the `then` calls, ...etc – trincot Jul 19 '20 at 17:46

1 Answers1

0

As evolutionxbox wrote, you need to return the promise returned by getLastUpdatedEnrollee as well as the promise getLastUpdatedEnrollee itself. In general, when calling a promise within a function, you need to return those promises in order to use those values outside of that function.

Here is your code with return added as needed:

let fetchEnrolleesData = () => {
    return getLastUpdatedEnrollee().then(res => {
        let params = path+"enrollees?limit=100";
        params += res.last_date ? "&last_updated_at=" + res.last_date.value : '';

        return fetchEnrolleesDataInStream(res, params).then(streamRes => {
            if(streamRes.length) {
                console.log(streamRes.length);
                return fetchEnrolleesData();
            }
        });
    });
}

As an optional side note, you may or may not prefer to use () => … syntax instead of () => { … } to remove the need to write return in the top-level function. You can do that in the top-level function because it has no other statements; this wouldn’t work in the inner function, which has multiple statements. See arrow function expressions for more detail.

let fetchEnrolleesData = () =>
    getLastUpdatedEnrollee().then(res => {
        // …
    });
Rory O'Kane
  • 29,210
  • 11
  • 96
  • 131