Question

How to use the retry from Rxjs to my await function?

I have to return an await function from my code block, now when the await function is called and failed on the first try, I want to retry it again and if it failed on the second time.. I will show an error message.

THIS IS MY CODE

async makeCall(inputs: myInputs): Promise<Instance> {

    const emailOptions: CreateOptions = {
      to: inputs.toPhone,
      from: this.config.accountPhoneNumber
    };

    if (inputs.toPhone) {
      emailOptions.sendText = inputs.toPhone;
    }

    return await this.sample.create(emailOptions);
}

I WANT SOMETHING LIKE THIS OR ANY SUGGESTION? LIKE Retry from RxJs

 for(var i = 0; i < 1; i++)
      {
        var result = await this.sample.create(emailOptions);
        if(result)
        {
          // break the loop
          return result;
        }
      }
       // if we land here, so the number of retries was exceeded
       throw Error("...");
 2  28  2
1 Jan 1970

Solution

 1

You can use this article code which seems to be exactly what you need. It has support for number of retries and custom error message.

import './style.css';
let i = 0;
const promiseFn = () => {
  const condition = i === 0;
  i++;
  return condition ? Promise.reject() : Promise.resolve();
};

const retryWithDelay = async (
  fn: any,
  retries = 3,
  finalErr = 'Retry failed'
) => {
  try {
    // try
    await fn();
  } catch (err) {
    // if no retries left
    // throw error
    if (retries <= 0) {
      console.log('error');
      return Promise.reject(finalErr);
    }
    //recursively call the same func
    return retryWithDelay(fn, retries - 1, finalErr);
  }
};

retryWithDelay(promiseFn, 2)
  .then(() => {
    console.log('final success');
  })
  .catch(() => {
    console.log('final error');
  });

Stackblitz Demo

2024-07-19
Naren Murali