Dev HelpersOpen library
← Back

Retry a failing operation

Retry a failing operation. A self-contained example using the JavaScript runtime.

Open this example in the interactive library

Source code

const retry = async (fn, n) => {
  for (let i = 0; ; i++) {
    try {
      return await fn();
    } catch (e) {
      if (i >= n) throw e;
    }
  }
};
let tries = 0;
console.log(
  await retry(async () => {
    if (++tries < 3) throw Error("retry");
    return "ready";
  }, 2),
  tries,
);

Sample output

ready 3