Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add optional delay for retry #335

Merged
merged 3 commits into from Mar 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Even better. Fixes an issue.


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