Commit 8a3e8db

Anton Medvedev <anton@medv.io>
2022-06-10 23:22:16
Add duration parsing to sleep()
1 parent db5ebba
src/goods.ts
@@ -16,9 +16,8 @@ import * as globbyModule from 'globby'
 import minimist from 'minimist'
 import nodeFetch, { RequestInfo, RequestInit } from 'node-fetch'
 import { createInterface } from 'node:readline'
-import { setTimeout as sleep } from 'node:timers/promises'
 import { $ } from './core.js'
-import { isString, stringify } from './util.js'
+import { Duration, isString, parseDuration, stringify } from './util.js'
 
 export { default as chalk } from 'chalk'
 export { default as fs } from 'fs-extra'
@@ -26,7 +25,6 @@ export { default as which } from 'which'
 export { default as YAML } from 'yaml'
 export { default as path } from 'node:path'
 export { default as os } from 'node:os'
-export { sleep }
 
 export const argv = minimist(process.argv.slice(2))
 
@@ -39,6 +37,12 @@ export const globby = Object.assign(function globby(
 globbyModule)
 export const glob = globby
 
+export function sleep(duration: Duration) {
+  return new Promise((resolve) => {
+    setTimeout(resolve, parseDuration(duration))
+  })
+}
+
 export async function fetch(url: RequestInfo, init?: RequestInit) {
   $.log({ kind: 'fetch', url, init })
   return nodeFetch(url, init)
test/cli.test.js
@@ -144,7 +144,6 @@ test('eval works with stdin', async () => {
   assert.is((await p).stdout, 'foobar\n')
 })
 
-
 test('executes a script from $PATH', async () => {
   const isWindows = process.platform === 'win32'
   const oldPath = process.env.PATH
test/goods.test.js
@@ -43,14 +43,14 @@ test('globby available', async () => {
   assert.equal(await globby('*.md'), ['README.md'])
 })
 
-test('fetch', async () => {
+test('fetch() works', async () => {
   assert.match(
     await fetch('https://medv.io').then((res) => res.text()),
     /Anton Medvedev/
   )
 })
 
-test('echo works', async () => {
+test('echo() works', async () => {
   let stdout = ''
   let log = console.log
   console.log = (...args) => {
@@ -75,4 +75,10 @@ test('which() available', async () => {
   assert.is(which.sync('npm'), await which('npm'))
 })
 
+test('sleep() works', async () => {
+  const now = Date.now()
+  await sleep(10)
+  assert.ok(Date.now() >= now + 10)
+})
+
 test.run()