diff --git a/README.md b/README.md index dee04a6a9c..4c2f3dd83d 100644 --- a/README.md +++ b/README.md @@ -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`. @@ -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()` diff --git a/experimental.d.ts b/experimental.d.ts index 1f9ef4cbd1..5e4b1a51a2 100644 --- a/experimental.d.ts +++ b/experimental.d.ts @@ -23,7 +23,7 @@ export const echo: Echo interface Retry { (pieces: TemplateStringsArray, ...args: any[]): Promise } -export const retry: (count: number) => Retry +export const retry: (count?: number, delay?: number) => Retry type StopSpinner = () => void export function startSpinner(title: string): StopSpinner diff --git a/experimental.mjs b/experimental.mjs index 03f3b29604..ffd15aa045 100644 --- a/experimental.mjs +++ b/experimental.mjs @@ -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) } } diff --git a/test.mjs b/test.mjs index fcbe193c50..90e239b4c2 100755 --- a/test.mjs +++ b/test.mjs @@ -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