Issue with awaiting promises in loop

Viewed 47

I have implemented retry logic for one API call like below:

private async fetchRecordingStatus(user: User): Promise<RecordingStatus[]> {
        const rs: RecordingStatus[] = [];
        let noOfRetries = 10;
        while (noOfRetries >= 0) {
            try {
                const userLineRecordingStatus = await this.getUserRecordingStatus(user.userid);
                 this.logger.log(`Preparing recording config status of userid:  ${hrUser.userid}`);

              // some processing  
                break;
            } catch (err) {
                if (noOfRetries === 0) {
                    throw err;
                } else {
                    this.logger.log(`Retry preparing recording config status of user: ${user.userid}`);
                    noOfRetries -= 1;
                    // wait for 2 seconds before trying
                    await new Promise(r => setTimeout(r, 2000));
                }
            }
        }
        return rs;
 }

In the above code I'm calling the fetchRecordingStatus method from client code(for around 10,000 users in a loop). However for some reason when the API call(getUserRecordingStatus) fails flow seems to hang instead of retrying the logic. In the logs I could see the retry statement printed once but that's it. Any ideas if I'm missing something? Thanks for your help.

DEMO:

async function fetchRecordingStatus(user) {
  const rs = [];
  let noOfRetries = 5;
  while (noOfRetries >= 0) {
    try {
      const userLineRecordingStatus = await Promise.reject(new Error('fail'));
      console.log(`Preparing recording config status of userid:`);

      // some processing  
      break;
    } catch (err) {
      if (noOfRetries === 0) {
        throw err;
      } else {
        console.log(`Retry preparing recording config status of user: `);
        noOfRetries -= 1;
        // wait for 2 seconds before trying
        await new Promise(r => setTimeout(r, 2000));
      }
    }
  }
  return rs;
}
fetchRecordingStatus()

0 Answers
Related