Retry promise until resolved (Too much recursion error)












0















I was trying to test if I could have a promise retry until it resolved, but it keeps giving "too much recursion" error and I can't understand why it doesn't stop after the 3rd recursion.



The following code is trying to emulate a failed query request to a server, which comes from a non-promise function.



function nonPromiseCallback(x, resolve, reject){    
if(x < 3){
reject(x)
}else{
resolve(x)
}
}

function tryUntilThree(x){
return new Promise( (resolve, reject) => {
nonPromiseCallback(x, resolve, tryUntilThree(x+1));
})
}

tryUntilThree(1)
.then(console.log);









share|improve this question




















  • 2





    check this answer, might help you

    – The Reason
    Jan 18 at 13:28











  • You get too much recursion because tryUntilThree is called too many times. Notice that you have written tryUntilThree(x+1), ie the engine has to resolve the call to tryUntilThree before it can call nonPromiseCallback. You have an infinite loop there.

    – some
    Jan 18 at 13:33











  • @some: Mind if i quote your comment in my answer? :)

    – vicbyte
    Jan 18 at 13:48











  • @vicbyte I don't mind. I added special quotes around the code (in my comment they where in italics)

    – some
    Jan 19 at 1:20
















0















I was trying to test if I could have a promise retry until it resolved, but it keeps giving "too much recursion" error and I can't understand why it doesn't stop after the 3rd recursion.



The following code is trying to emulate a failed query request to a server, which comes from a non-promise function.



function nonPromiseCallback(x, resolve, reject){    
if(x < 3){
reject(x)
}else{
resolve(x)
}
}

function tryUntilThree(x){
return new Promise( (resolve, reject) => {
nonPromiseCallback(x, resolve, tryUntilThree(x+1));
})
}

tryUntilThree(1)
.then(console.log);









share|improve this question




















  • 2





    check this answer, might help you

    – The Reason
    Jan 18 at 13:28











  • You get too much recursion because tryUntilThree is called too many times. Notice that you have written tryUntilThree(x+1), ie the engine has to resolve the call to tryUntilThree before it can call nonPromiseCallback. You have an infinite loop there.

    – some
    Jan 18 at 13:33











  • @some: Mind if i quote your comment in my answer? :)

    – vicbyte
    Jan 18 at 13:48











  • @vicbyte I don't mind. I added special quotes around the code (in my comment they where in italics)

    – some
    Jan 19 at 1:20














0












0








0








I was trying to test if I could have a promise retry until it resolved, but it keeps giving "too much recursion" error and I can't understand why it doesn't stop after the 3rd recursion.



The following code is trying to emulate a failed query request to a server, which comes from a non-promise function.



function nonPromiseCallback(x, resolve, reject){    
if(x < 3){
reject(x)
}else{
resolve(x)
}
}

function tryUntilThree(x){
return new Promise( (resolve, reject) => {
nonPromiseCallback(x, resolve, tryUntilThree(x+1));
})
}

tryUntilThree(1)
.then(console.log);









share|improve this question
















I was trying to test if I could have a promise retry until it resolved, but it keeps giving "too much recursion" error and I can't understand why it doesn't stop after the 3rd recursion.



The following code is trying to emulate a failed query request to a server, which comes from a non-promise function.



function nonPromiseCallback(x, resolve, reject){    
if(x < 3){
reject(x)
}else{
resolve(x)
}
}

function tryUntilThree(x){
return new Promise( (resolve, reject) => {
nonPromiseCallback(x, resolve, tryUntilThree(x+1));
})
}

tryUntilThree(1)
.then(console.log);






javascript ecmascript-6 es6-promise






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 18 at 13:26







Mojimi

















asked Jan 18 at 13:02









MojimiMojimi

247831




247831








  • 2





    check this answer, might help you

    – The Reason
    Jan 18 at 13:28











  • You get too much recursion because tryUntilThree is called too many times. Notice that you have written tryUntilThree(x+1), ie the engine has to resolve the call to tryUntilThree before it can call nonPromiseCallback. You have an infinite loop there.

    – some
    Jan 18 at 13:33











  • @some: Mind if i quote your comment in my answer? :)

    – vicbyte
    Jan 18 at 13:48











  • @vicbyte I don't mind. I added special quotes around the code (in my comment they where in italics)

    – some
    Jan 19 at 1:20














  • 2





    check this answer, might help you

    – The Reason
    Jan 18 at 13:28











  • You get too much recursion because tryUntilThree is called too many times. Notice that you have written tryUntilThree(x+1), ie the engine has to resolve the call to tryUntilThree before it can call nonPromiseCallback. You have an infinite loop there.

    – some
    Jan 18 at 13:33











  • @some: Mind if i quote your comment in my answer? :)

    – vicbyte
    Jan 18 at 13:48











  • @vicbyte I don't mind. I added special quotes around the code (in my comment they where in italics)

    – some
    Jan 19 at 1:20








2




2





check this answer, might help you

– The Reason
Jan 18 at 13:28





check this answer, might help you

– The Reason
Jan 18 at 13:28













You get too much recursion because tryUntilThree is called too many times. Notice that you have written tryUntilThree(x+1), ie the engine has to resolve the call to tryUntilThree before it can call nonPromiseCallback. You have an infinite loop there.

– some
Jan 18 at 13:33





You get too much recursion because tryUntilThree is called too many times. Notice that you have written tryUntilThree(x+1), ie the engine has to resolve the call to tryUntilThree before it can call nonPromiseCallback. You have an infinite loop there.

– some
Jan 18 at 13:33













@some: Mind if i quote your comment in my answer? :)

– vicbyte
Jan 18 at 13:48





@some: Mind if i quote your comment in my answer? :)

– vicbyte
Jan 18 at 13:48













@vicbyte I don't mind. I added special quotes around the code (in my comment they where in italics)

– some
Jan 19 at 1:20





@vicbyte I don't mind. I added special quotes around the code (in my comment they where in italics)

– some
Jan 19 at 1:20












4 Answers
4






active

oldest

votes


















3














Since you are interested in a promise failure, you could use the catch handler.



As to why your code doesn't work, heres a good explaination by some (also in the comment):




You get too much recursion because tryUntilThree is called too many
times. Notice that you have written tryUntilThree(x+1), ie the engine
has to resolve the call to tryUntilThree before it can call
nonPromiseCallback. You have an infinite loop there.







function nonPromiseCallback(x, resolve, reject){    
if(x < 3){
reject(x)
}else{
resolve(x)
}
}

function tryUntilThree(x){
return new Promise( (resolve, reject) =>
nonPromiseCallback(x, resolve, reject)
).catch(() =>
tryUntilThree(x + 1)
)
}

tryUntilThree(1)
.then(console.log);








share|improve this answer

































    1














    The problem is with the nonPromiseCallback method call, instead of a function reference, you are passing an actual function and then calling that function.



    Problem:



    nonPromiseCallback(x, resolve, tryUntilThree(x+1));


    Fix:



    nonPromiseCallback(x, resolve, tryUntilThree);


    and



    reject(x+1);





    share|improve this answer
























    • This doesn't actually work either.

      – Bergi
      Jan 18 at 13:37











    • @Bergi I pointed the fix for the call stack issue he is facing (infinite recursion), I haven't pointed out any thing else since I don't know what he wants from the code.

      – Danyal Imran
      Jan 18 at 13:38













    • I want the code to compile... and to print 3

      – Mojimi
      Jan 18 at 13:43



















    1














    I tried your code but got the TypeError: reject is not a function.
    That is because you pass in tryUntilThree(x+1) which executes the function before passing it to nonPromiseCallback.



    So i came up with this code, to try to accomplish what you want.



    let res;    // used for keeping a reference to the original resolve
    function nonPromiseCallback(x, resolve, reject){
    if(x < 3){
    reject(x + 1);
    }
    else{
    resolve(x);
    }
    }

    function tryUntilThree(x){
    return new Promise((resolve) => {
    if(!res){
    res = resolve;
    }
    nonPromiseCallback(x, res, tryUntilThree);
    });
    }

    tryUntilThree(1)
    .then(res => console.log("RESULT:", res));


    let res;, this variable is used for keeping a reference to the original resolve, so that the .then executes.






    share|improve this answer































      1














      As I said in my comment, to your question, you had an infinite loop since to call nonPromiseCallback the result of tryUntilThree was needed... and to get that, tryUntilThree was called... and it was looping until memory was exhausted or the end of the universe, whichever came first.



      You need to make two changes:



      function nonPromiseCallback(x, resolve, reject){
      if(x < 3){
      reject(x+1) // the increment of x is moved to here.
      }else{
      resolve(x)
      }
      }

      function tryUntilThree(x){
      return new Promise( (resolve, reject) => {
      nonPromiseCallback(x, resolve, tryUntilThree); // Just pass the function, it will be called later
      })
      }

      tryUntilThree(1)
      .then(console.log);


      If you can use async and await (new features since 2017) you could solve it like this (I moved the decision of maximum number of tries to the calling function) :



      function nonPromiseCallback(x, resolve, reject){
      if(x < 3){
      reject(x+1)
      }else{
      resolve(x)
      }
      }

      async function tryUntilThree(){
      const maxAttempts = 3;
      let attempt = 1;

      do {
      try {
      // "await" waits for the prommise to resolve or reject.
      // If it is rejected, an error will be thrown. That's why
      // this part of the code is inside a try/catch-block.
      const result = await new Promise( (resolve, reject) =>
      nonPromiseCallback( attempt, resolve, reject )
      );
      return result; // Return the result from nonPromiseCallback
      }
      catch (error) {
      // The nonPromiseCallback failed. Try again
      attempt += 1;
      }
      } while ( attempt <= maxAttempts );

      // Signal error after all retires.
      throw Error(`Failure, even after ${maxAttempts} tries`);
      }

      tryUntilThree()
      .then(console.log);





      share|improve this answer























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54254568%2fretry-promise-until-resolved-too-much-recursion-error%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        3














        Since you are interested in a promise failure, you could use the catch handler.



        As to why your code doesn't work, heres a good explaination by some (also in the comment):




        You get too much recursion because tryUntilThree is called too many
        times. Notice that you have written tryUntilThree(x+1), ie the engine
        has to resolve the call to tryUntilThree before it can call
        nonPromiseCallback. You have an infinite loop there.







        function nonPromiseCallback(x, resolve, reject){    
        if(x < 3){
        reject(x)
        }else{
        resolve(x)
        }
        }

        function tryUntilThree(x){
        return new Promise( (resolve, reject) =>
        nonPromiseCallback(x, resolve, reject)
        ).catch(() =>
        tryUntilThree(x + 1)
        )
        }

        tryUntilThree(1)
        .then(console.log);








        share|improve this answer






























          3














          Since you are interested in a promise failure, you could use the catch handler.



          As to why your code doesn't work, heres a good explaination by some (also in the comment):




          You get too much recursion because tryUntilThree is called too many
          times. Notice that you have written tryUntilThree(x+1), ie the engine
          has to resolve the call to tryUntilThree before it can call
          nonPromiseCallback. You have an infinite loop there.







          function nonPromiseCallback(x, resolve, reject){    
          if(x < 3){
          reject(x)
          }else{
          resolve(x)
          }
          }

          function tryUntilThree(x){
          return new Promise( (resolve, reject) =>
          nonPromiseCallback(x, resolve, reject)
          ).catch(() =>
          tryUntilThree(x + 1)
          )
          }

          tryUntilThree(1)
          .then(console.log);








          share|improve this answer




























            3












            3








            3







            Since you are interested in a promise failure, you could use the catch handler.



            As to why your code doesn't work, heres a good explaination by some (also in the comment):




            You get too much recursion because tryUntilThree is called too many
            times. Notice that you have written tryUntilThree(x+1), ie the engine
            has to resolve the call to tryUntilThree before it can call
            nonPromiseCallback. You have an infinite loop there.







            function nonPromiseCallback(x, resolve, reject){    
            if(x < 3){
            reject(x)
            }else{
            resolve(x)
            }
            }

            function tryUntilThree(x){
            return new Promise( (resolve, reject) =>
            nonPromiseCallback(x, resolve, reject)
            ).catch(() =>
            tryUntilThree(x + 1)
            )
            }

            tryUntilThree(1)
            .then(console.log);








            share|improve this answer















            Since you are interested in a promise failure, you could use the catch handler.



            As to why your code doesn't work, heres a good explaination by some (also in the comment):




            You get too much recursion because tryUntilThree is called too many
            times. Notice that you have written tryUntilThree(x+1), ie the engine
            has to resolve the call to tryUntilThree before it can call
            nonPromiseCallback. You have an infinite loop there.







            function nonPromiseCallback(x, resolve, reject){    
            if(x < 3){
            reject(x)
            }else{
            resolve(x)
            }
            }

            function tryUntilThree(x){
            return new Promise( (resolve, reject) =>
            nonPromiseCallback(x, resolve, reject)
            ).catch(() =>
            tryUntilThree(x + 1)
            )
            }

            tryUntilThree(1)
            .then(console.log);








            function nonPromiseCallback(x, resolve, reject){    
            if(x < 3){
            reject(x)
            }else{
            resolve(x)
            }
            }

            function tryUntilThree(x){
            return new Promise( (resolve, reject) =>
            nonPromiseCallback(x, resolve, reject)
            ).catch(() =>
            tryUntilThree(x + 1)
            )
            }

            tryUntilThree(1)
            .then(console.log);





            function nonPromiseCallback(x, resolve, reject){    
            if(x < 3){
            reject(x)
            }else{
            resolve(x)
            }
            }

            function tryUntilThree(x){
            return new Promise( (resolve, reject) =>
            nonPromiseCallback(x, resolve, reject)
            ).catch(() =>
            tryUntilThree(x + 1)
            )
            }

            tryUntilThree(1)
            .then(console.log);






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jan 19 at 1:19









            some

            35.4k116479




            35.4k116479










            answered Jan 18 at 13:44









            vicbytevicbyte

            2,6011313




            2,6011313

























                1














                The problem is with the nonPromiseCallback method call, instead of a function reference, you are passing an actual function and then calling that function.



                Problem:



                nonPromiseCallback(x, resolve, tryUntilThree(x+1));


                Fix:



                nonPromiseCallback(x, resolve, tryUntilThree);


                and



                reject(x+1);





                share|improve this answer
























                • This doesn't actually work either.

                  – Bergi
                  Jan 18 at 13:37











                • @Bergi I pointed the fix for the call stack issue he is facing (infinite recursion), I haven't pointed out any thing else since I don't know what he wants from the code.

                  – Danyal Imran
                  Jan 18 at 13:38













                • I want the code to compile... and to print 3

                  – Mojimi
                  Jan 18 at 13:43
















                1














                The problem is with the nonPromiseCallback method call, instead of a function reference, you are passing an actual function and then calling that function.



                Problem:



                nonPromiseCallback(x, resolve, tryUntilThree(x+1));


                Fix:



                nonPromiseCallback(x, resolve, tryUntilThree);


                and



                reject(x+1);





                share|improve this answer
























                • This doesn't actually work either.

                  – Bergi
                  Jan 18 at 13:37











                • @Bergi I pointed the fix for the call stack issue he is facing (infinite recursion), I haven't pointed out any thing else since I don't know what he wants from the code.

                  – Danyal Imran
                  Jan 18 at 13:38













                • I want the code to compile... and to print 3

                  – Mojimi
                  Jan 18 at 13:43














                1












                1








                1







                The problem is with the nonPromiseCallback method call, instead of a function reference, you are passing an actual function and then calling that function.



                Problem:



                nonPromiseCallback(x, resolve, tryUntilThree(x+1));


                Fix:



                nonPromiseCallback(x, resolve, tryUntilThree);


                and



                reject(x+1);





                share|improve this answer













                The problem is with the nonPromiseCallback method call, instead of a function reference, you are passing an actual function and then calling that function.



                Problem:



                nonPromiseCallback(x, resolve, tryUntilThree(x+1));


                Fix:



                nonPromiseCallback(x, resolve, tryUntilThree);


                and



                reject(x+1);






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jan 18 at 13:36









                Danyal ImranDanyal Imran

                1,145214




                1,145214













                • This doesn't actually work either.

                  – Bergi
                  Jan 18 at 13:37











                • @Bergi I pointed the fix for the call stack issue he is facing (infinite recursion), I haven't pointed out any thing else since I don't know what he wants from the code.

                  – Danyal Imran
                  Jan 18 at 13:38













                • I want the code to compile... and to print 3

                  – Mojimi
                  Jan 18 at 13:43



















                • This doesn't actually work either.

                  – Bergi
                  Jan 18 at 13:37











                • @Bergi I pointed the fix for the call stack issue he is facing (infinite recursion), I haven't pointed out any thing else since I don't know what he wants from the code.

                  – Danyal Imran
                  Jan 18 at 13:38













                • I want the code to compile... and to print 3

                  – Mojimi
                  Jan 18 at 13:43

















                This doesn't actually work either.

                – Bergi
                Jan 18 at 13:37





                This doesn't actually work either.

                – Bergi
                Jan 18 at 13:37













                @Bergi I pointed the fix for the call stack issue he is facing (infinite recursion), I haven't pointed out any thing else since I don't know what he wants from the code.

                – Danyal Imran
                Jan 18 at 13:38







                @Bergi I pointed the fix for the call stack issue he is facing (infinite recursion), I haven't pointed out any thing else since I don't know what he wants from the code.

                – Danyal Imran
                Jan 18 at 13:38















                I want the code to compile... and to print 3

                – Mojimi
                Jan 18 at 13:43





                I want the code to compile... and to print 3

                – Mojimi
                Jan 18 at 13:43











                1














                I tried your code but got the TypeError: reject is not a function.
                That is because you pass in tryUntilThree(x+1) which executes the function before passing it to nonPromiseCallback.



                So i came up with this code, to try to accomplish what you want.



                let res;    // used for keeping a reference to the original resolve
                function nonPromiseCallback(x, resolve, reject){
                if(x < 3){
                reject(x + 1);
                }
                else{
                resolve(x);
                }
                }

                function tryUntilThree(x){
                return new Promise((resolve) => {
                if(!res){
                res = resolve;
                }
                nonPromiseCallback(x, res, tryUntilThree);
                });
                }

                tryUntilThree(1)
                .then(res => console.log("RESULT:", res));


                let res;, this variable is used for keeping a reference to the original resolve, so that the .then executes.






                share|improve this answer




























                  1














                  I tried your code but got the TypeError: reject is not a function.
                  That is because you pass in tryUntilThree(x+1) which executes the function before passing it to nonPromiseCallback.



                  So i came up with this code, to try to accomplish what you want.



                  let res;    // used for keeping a reference to the original resolve
                  function nonPromiseCallback(x, resolve, reject){
                  if(x < 3){
                  reject(x + 1);
                  }
                  else{
                  resolve(x);
                  }
                  }

                  function tryUntilThree(x){
                  return new Promise((resolve) => {
                  if(!res){
                  res = resolve;
                  }
                  nonPromiseCallback(x, res, tryUntilThree);
                  });
                  }

                  tryUntilThree(1)
                  .then(res => console.log("RESULT:", res));


                  let res;, this variable is used for keeping a reference to the original resolve, so that the .then executes.






                  share|improve this answer


























                    1












                    1








                    1







                    I tried your code but got the TypeError: reject is not a function.
                    That is because you pass in tryUntilThree(x+1) which executes the function before passing it to nonPromiseCallback.



                    So i came up with this code, to try to accomplish what you want.



                    let res;    // used for keeping a reference to the original resolve
                    function nonPromiseCallback(x, resolve, reject){
                    if(x < 3){
                    reject(x + 1);
                    }
                    else{
                    resolve(x);
                    }
                    }

                    function tryUntilThree(x){
                    return new Promise((resolve) => {
                    if(!res){
                    res = resolve;
                    }
                    nonPromiseCallback(x, res, tryUntilThree);
                    });
                    }

                    tryUntilThree(1)
                    .then(res => console.log("RESULT:", res));


                    let res;, this variable is used for keeping a reference to the original resolve, so that the .then executes.






                    share|improve this answer













                    I tried your code but got the TypeError: reject is not a function.
                    That is because you pass in tryUntilThree(x+1) which executes the function before passing it to nonPromiseCallback.



                    So i came up with this code, to try to accomplish what you want.



                    let res;    // used for keeping a reference to the original resolve
                    function nonPromiseCallback(x, resolve, reject){
                    if(x < 3){
                    reject(x + 1);
                    }
                    else{
                    resolve(x);
                    }
                    }

                    function tryUntilThree(x){
                    return new Promise((resolve) => {
                    if(!res){
                    res = resolve;
                    }
                    nonPromiseCallback(x, res, tryUntilThree);
                    });
                    }

                    tryUntilThree(1)
                    .then(res => console.log("RESULT:", res));


                    let res;, this variable is used for keeping a reference to the original resolve, so that the .then executes.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Jan 18 at 13:41









                    robbannnrobbannn

                    3,41111935




                    3,41111935























                        1














                        As I said in my comment, to your question, you had an infinite loop since to call nonPromiseCallback the result of tryUntilThree was needed... and to get that, tryUntilThree was called... and it was looping until memory was exhausted or the end of the universe, whichever came first.



                        You need to make two changes:



                        function nonPromiseCallback(x, resolve, reject){
                        if(x < 3){
                        reject(x+1) // the increment of x is moved to here.
                        }else{
                        resolve(x)
                        }
                        }

                        function tryUntilThree(x){
                        return new Promise( (resolve, reject) => {
                        nonPromiseCallback(x, resolve, tryUntilThree); // Just pass the function, it will be called later
                        })
                        }

                        tryUntilThree(1)
                        .then(console.log);


                        If you can use async and await (new features since 2017) you could solve it like this (I moved the decision of maximum number of tries to the calling function) :



                        function nonPromiseCallback(x, resolve, reject){
                        if(x < 3){
                        reject(x+1)
                        }else{
                        resolve(x)
                        }
                        }

                        async function tryUntilThree(){
                        const maxAttempts = 3;
                        let attempt = 1;

                        do {
                        try {
                        // "await" waits for the prommise to resolve or reject.
                        // If it is rejected, an error will be thrown. That's why
                        // this part of the code is inside a try/catch-block.
                        const result = await new Promise( (resolve, reject) =>
                        nonPromiseCallback( attempt, resolve, reject )
                        );
                        return result; // Return the result from nonPromiseCallback
                        }
                        catch (error) {
                        // The nonPromiseCallback failed. Try again
                        attempt += 1;
                        }
                        } while ( attempt <= maxAttempts );

                        // Signal error after all retires.
                        throw Error(`Failure, even after ${maxAttempts} tries`);
                        }

                        tryUntilThree()
                        .then(console.log);





                        share|improve this answer




























                          1














                          As I said in my comment, to your question, you had an infinite loop since to call nonPromiseCallback the result of tryUntilThree was needed... and to get that, tryUntilThree was called... and it was looping until memory was exhausted or the end of the universe, whichever came first.



                          You need to make two changes:



                          function nonPromiseCallback(x, resolve, reject){
                          if(x < 3){
                          reject(x+1) // the increment of x is moved to here.
                          }else{
                          resolve(x)
                          }
                          }

                          function tryUntilThree(x){
                          return new Promise( (resolve, reject) => {
                          nonPromiseCallback(x, resolve, tryUntilThree); // Just pass the function, it will be called later
                          })
                          }

                          tryUntilThree(1)
                          .then(console.log);


                          If you can use async and await (new features since 2017) you could solve it like this (I moved the decision of maximum number of tries to the calling function) :



                          function nonPromiseCallback(x, resolve, reject){
                          if(x < 3){
                          reject(x+1)
                          }else{
                          resolve(x)
                          }
                          }

                          async function tryUntilThree(){
                          const maxAttempts = 3;
                          let attempt = 1;

                          do {
                          try {
                          // "await" waits for the prommise to resolve or reject.
                          // If it is rejected, an error will be thrown. That's why
                          // this part of the code is inside a try/catch-block.
                          const result = await new Promise( (resolve, reject) =>
                          nonPromiseCallback( attempt, resolve, reject )
                          );
                          return result; // Return the result from nonPromiseCallback
                          }
                          catch (error) {
                          // The nonPromiseCallback failed. Try again
                          attempt += 1;
                          }
                          } while ( attempt <= maxAttempts );

                          // Signal error after all retires.
                          throw Error(`Failure, even after ${maxAttempts} tries`);
                          }

                          tryUntilThree()
                          .then(console.log);





                          share|improve this answer


























                            1












                            1








                            1







                            As I said in my comment, to your question, you had an infinite loop since to call nonPromiseCallback the result of tryUntilThree was needed... and to get that, tryUntilThree was called... and it was looping until memory was exhausted or the end of the universe, whichever came first.



                            You need to make two changes:



                            function nonPromiseCallback(x, resolve, reject){
                            if(x < 3){
                            reject(x+1) // the increment of x is moved to here.
                            }else{
                            resolve(x)
                            }
                            }

                            function tryUntilThree(x){
                            return new Promise( (resolve, reject) => {
                            nonPromiseCallback(x, resolve, tryUntilThree); // Just pass the function, it will be called later
                            })
                            }

                            tryUntilThree(1)
                            .then(console.log);


                            If you can use async and await (new features since 2017) you could solve it like this (I moved the decision of maximum number of tries to the calling function) :



                            function nonPromiseCallback(x, resolve, reject){
                            if(x < 3){
                            reject(x+1)
                            }else{
                            resolve(x)
                            }
                            }

                            async function tryUntilThree(){
                            const maxAttempts = 3;
                            let attempt = 1;

                            do {
                            try {
                            // "await" waits for the prommise to resolve or reject.
                            // If it is rejected, an error will be thrown. That's why
                            // this part of the code is inside a try/catch-block.
                            const result = await new Promise( (resolve, reject) =>
                            nonPromiseCallback( attempt, resolve, reject )
                            );
                            return result; // Return the result from nonPromiseCallback
                            }
                            catch (error) {
                            // The nonPromiseCallback failed. Try again
                            attempt += 1;
                            }
                            } while ( attempt <= maxAttempts );

                            // Signal error after all retires.
                            throw Error(`Failure, even after ${maxAttempts} tries`);
                            }

                            tryUntilThree()
                            .then(console.log);





                            share|improve this answer













                            As I said in my comment, to your question, you had an infinite loop since to call nonPromiseCallback the result of tryUntilThree was needed... and to get that, tryUntilThree was called... and it was looping until memory was exhausted or the end of the universe, whichever came first.



                            You need to make two changes:



                            function nonPromiseCallback(x, resolve, reject){
                            if(x < 3){
                            reject(x+1) // the increment of x is moved to here.
                            }else{
                            resolve(x)
                            }
                            }

                            function tryUntilThree(x){
                            return new Promise( (resolve, reject) => {
                            nonPromiseCallback(x, resolve, tryUntilThree); // Just pass the function, it will be called later
                            })
                            }

                            tryUntilThree(1)
                            .then(console.log);


                            If you can use async and await (new features since 2017) you could solve it like this (I moved the decision of maximum number of tries to the calling function) :



                            function nonPromiseCallback(x, resolve, reject){
                            if(x < 3){
                            reject(x+1)
                            }else{
                            resolve(x)
                            }
                            }

                            async function tryUntilThree(){
                            const maxAttempts = 3;
                            let attempt = 1;

                            do {
                            try {
                            // "await" waits for the prommise to resolve or reject.
                            // If it is rejected, an error will be thrown. That's why
                            // this part of the code is inside a try/catch-block.
                            const result = await new Promise( (resolve, reject) =>
                            nonPromiseCallback( attempt, resolve, reject )
                            );
                            return result; // Return the result from nonPromiseCallback
                            }
                            catch (error) {
                            // The nonPromiseCallback failed. Try again
                            attempt += 1;
                            }
                            } while ( attempt <= maxAttempts );

                            // Signal error after all retires.
                            throw Error(`Failure, even after ${maxAttempts} tries`);
                            }

                            tryUntilThree()
                            .then(console.log);






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jan 19 at 2:01









                            somesome

                            35.4k116479




                            35.4k116479






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54254568%2fretry-promise-until-resolved-too-much-recursion-error%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown