Skip to content

Instantly share code, notes, and snippets.

@tjunghans
Created May 22, 2017 13:39
Show Gist options
  • Save tjunghans/ad0fb2b375cc1c06000d4da2ec4c37b2 to your computer and use it in GitHub Desktop.
Save tjunghans/ad0fb2b375cc1c06000d4da2ec4c37b2 to your computer and use it in GitHub Desktop.
Recursive Promises

Recursive Promises

You have a function authenticate which returns a resolved promise on success or reject on failure. If the authentication failed the process should be repeated. This can be a achieved with a recursive promise.

Example

let counter = 0;

function login() {
  return new Promise((resolve, reject) => {
   if (counter === 0) { // will be true on the first call
     counter++; 
     reject(new Error("Error logging in, please try again"));
   } else {
     resolve("Success");
   }
  })
  .catch(err => {
    console.log("Caught");
    return login();
  });
}

login().then((res) => {
  console.log("Success", res);
}).catch(err => {
  console.log("Error", err);
});

// The above will log
// Caught
// Success success
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment