Web User
Web User

Reputation: 7736

Implement polling mechanism within a JavaScript promise chain

I am writing a node.js (v12.13.0) script that involves a REST API. Imagine the following sequence of tasks, to be performed in the same order:

Task 1
 |
User Action
 |
Task 2
 |
Task 3

User Action and Task 2 must be completed within 10 minutes of the generation of the 5-digit alphanumeric code in Task 1. Since Tasks 1, 2 and 3 are performed within a script, there is no way of knowing exactly when a user completes User Action. So, the only option is for Task 2 to repeatedly call the REST API until an OAuth2 authorization code is generated. If 10 minutes has elapsed and the REST API continues to yield an error, then the script must stop since it cannot perform Task 3.

I tried implementing this using JavaScript's Promise (ES 6) and setInterval along the following lines:

const fnPerformTask1 = () => {
  return new Promise((resolve, reject) => {
    /*
      code goes here, to call REST API and obtain a 5-digit alphanumeric code
     */

    resolve({
      "code": "<5_digit_apha_code>"
      "genTime": new Date()
    })
  });
}

const fnPerformTask2 = (task1Result) => {
  return new Promise((resolve, reject) => {
    /*
      (a) code goes here, to call REST API and obtain an OAuth2 authorization code
      (b) if REST API returns error _and_ 10 minutes have not yet elapsed, repeat step (a)
     */
    resolve(<authorization_code>);
  });
}

const fnPerformTask3 = (task2Result) => {
  return new Promise(resolve, reject) => {
    /*
      code goes here, to call REST API and obtain OAuth2 tokens
     */
    resolve(<tokens>);
  });
}

fnPerformTask1()
  .then(fnPerformTask2)
  .catch(console.error) // if Task 2 fails, break out of this promise chain and don't perform Task 3
  .then(fnPerformTask3)
  .then(console.info)
  .catch(console.error);

Can I implement some kind of a poll-like mechanism in Task 2, using Promise and setInterval, and clear the interval when either the REST API returns an authorization code, or 10 minutes has elapsed without receiving an authorization code... presumably because the user did not complete User Action within 10 minutes?

A second, related question is how do I break out of a promise chain if Task 2 cannot be completed?

Upvotes: 0

Views: 117

Answers (1)

laxman
laxman

Reputation: 2110

how do I break out of a promise chain if Task 2 cannot be completed?

fnPerformTask1()
.then(fnPerformTask2)
.catch(err => throw err) // this will break the promise chain and the control will move to subsequent .catch()
.then(fnPerformTask3)
.then(console.info)
.catch((err) => console.log("potential error thrown from fnPerformTask2"));

Upvotes: 1

Related Questions