Code Lab

Modo entrevista. Temporizador de 10 min, sin pistas y sin autocompletado

Retry on failure

MediaAsync code10 min

Write a function retry(fn). It calls the async function fn with no arguments. If the promise from fn rejects, call fn again. Make no more than three attempts in total.

retry returns a promise with the result of the first successful attempt. If all three attempts fail, return a promise that rejects with the error of the last attempt.

Ejemplos

await retry(() => Promise.resolve('ok'))

Devuelve 'ok'

The first attempt succeeds, so there is no retry.
await retry(() => Promise.reject(new Error('down'))).catch((e) => e.message)

Devuelve 'down'

All three attempts fail, and the last error comes out.

Fuente

Cargando el editor…
  1. Success on the first try, fn is called once
  2. Two failures, then success
  3. Three failures, the last error comes out

Las pruebas ocultas se ejecutan al enviar