promise-assist
Several helper functions when working with native promises.
API
sleep
Useful for waiting a specific amount of time before continuing an operation.
import { sleep } from 'promise-assist'
async function myOperation() {
const startTime = Date.now()
await sleep(500)
console.log(`${Date.now() - startTime}ms passed!`)
}
timeout
Useful for limiting the amount of time an async Promise-based operation can take.
import { timeout } from 'promise-assist'
async function myOperation() {
try {
const data = await timeout(
fetchDataFromServer(),
10000,
`failed loading required data from backend`
)
} catch (e) {
}
}
deferred
Creates a deferred Promise, where resolve
/reject
are exposed to the place that holds the promise.
Generally a bad practice, but there are use-cases, such as mixing callback-based and Promise-based APIs, where this is helpful.
import { deferred } from 'promise-assist'
const { promise, resolve, reject } = deferred<string>()
promise.then(value => console.log(value))
resolve('some text')
retry
Executes provided action
(sync or async) and returns its value.
If action
throws or rejects, it will retry execution several times before failing.
Defaults are:
- 3 retries
- no delay between retries
- no timeout to stop trying
These can be customized via a second optional options
parameter.
import { retry } from 'promise-assist'
retry(() => fetch('http://some-url/asset.json'))
.then(value => value.json())
.then(console.log)
.catch(e => console.error(e))
retry(() => fetch('http://some-url/asset.json'), {
retries: -1,
delay: 10 * 1000,
timeout: 2 * 60 * 1000
})
.then(value => value.json())
.then(console.log)
.catch(e => console.error(e))
License
MIT