Search code examples
javascriptnode.jsrecursionpromisees6-promise

Use promises with recursive function


I am trying to figure out if it's possible to use promises instead of a standard callback in a recursive function.

The way I have it now:

function recursive(data, cb){

     (function promiseProvider(data){

          return newThenable(data).then(function(val){
                 if(val.a){
                    cb(null, val);
                 }
                 else {
                    return promiseProvider(val);
                 }

          });

     })(data);

}

This works, but I can't figure out how I could make a pure promise implementation.

Perhaps this would work?

  function recursive(data){

      return newThenable(data).then(function(val){
               if(val.a){
                  return // <<< ???
                 }
                 else {
                   return recursive(val);
                 }

        });

     }

However, that doesn't work.


Solution

  • Given you were calling the callback with val as the result argument, just

    return val;
    

    from the then callback. That's it.

    function recursive(data){
         return newThenable(data).then(function(val){
             if (val.a){
                 return val;
             } else {
                 return recursive(val);
             }
         });
     }