Skip to content

Commit

Permalink
feat: add optional delay for retry (#335)
Browse files Browse the repository at this point in the history
* feat: add optional delay for `retry`

* chore: simplify retry type decl
  • Loading branch information
antongolub committed Mar 13, 2022
1 parent 0b3659f commit 450917a
Show file tree
Hide file tree
Showing 4 changed files with 10 additions and 4 deletions.
5 changes: 4 additions & 1 deletion README.md
Expand Up @@ -312,7 +312,7 @@ $.shell = '/usr/bin/bash'

Or use a CLI argument: `--shell=/bin/bash`

#### `$.spanw`
#### `$.spawn`

Specifies a `spawn` api. Defaults to `require('child_process').spawn`.

Expand Down Expand Up @@ -371,6 +371,9 @@ successful attempt, or will throw after specifies attempts count.
import {retry} from 'zx/experimental'

let {stdout} = await retry(5)`curl localhost`

// with a specified delay between attempts
let {stdout} = await retry(3, 500)`npm whoami`
```
#### `echo()`
Expand Down
2 changes: 1 addition & 1 deletion experimental.d.ts
Expand Up @@ -23,7 +23,7 @@ export const echo: Echo
interface Retry {
(pieces: TemplateStringsArray, ...args: any[]): Promise<ProcessOutput>
}
export const retry: (count: number) => Retry
export const retry: (count?: number, delay?: number) => Retry

type StopSpinner = () => void
export function startSpinner(title: string): StopSpinner
3 changes: 2 additions & 1 deletion experimental.mjs
Expand Up @@ -16,11 +16,12 @@ import {ProcessOutput} from './index.mjs'

// Retries a command a few times. Will return after the first
// successful attempt, or will throw after specifies attempts count.
export const retry = (count = 5) => async (cmd, ...args) => {
export const retry = (count = 5, delay = 0) => async (cmd, ...args) => {
while (count --> 0) try {
return await $(cmd, ...args)
} catch (p) {
if (count === 0) throw p
if (delay) await sleep(delay)
}
}

Expand Down
4 changes: 3 additions & 1 deletion test.mjs
Expand Up @@ -241,12 +241,14 @@ if (test('YAML works')) {

if (test('Retry works')) {
let exitCode = 0
let now = Date.now()
try {
await retry(5)`exit 123`
await retry(5, 50)`exit 123`
} catch (p) {
exitCode = p.exitCode
}
assert.equal(exitCode, 123)
assert(Date.now() >= now + 50 * (5 - 1))
}

let version
Expand Down

0 comments on commit 450917a

Please sign in to comment.