defer
Defer work until an async function completes
415 bytes
Usage
The defer
function allows you to run an async function while registering cleanup functions that will execute after it completes. This is useful when you need to clean up resources regardless of whether the main function succeeds or fails, similar to a finally
block.
The function passed to defer
receives a register
function as its argument. Use this to register cleanup work that should run after the main function finishes.
By default, if a cleanup function throws an error after the main function has thrown an error, the cleanup error will be ignored. You can customize this behavior by passing { rethrow: true }
to the register
function to have it rethrow cleanup errors instead.
Clean up temporary files
import * as _ from 'radashi'
// Placeholder functionsconst createBuildDir = async () => { console.log('Creating build directory...') await _.sleep(100) console.log('Build directory created.') return 'build'}const build = async () => { console.log('Building project...') await _.sleep(100) console.log('Project built.')}
await _.defer(async cleanup => { const buildDir = await createBuildDir()
cleanup(() => fs.unlink(buildDir))
await build()})
Clean up resources in an API
// Placeholder APIconst api = { org: { create: async () => ({ id: 1 }), delete: async () => { console.log('Deleting organization...') await _.sleep(100) console.log('Deleted organization.') }, }, user: { create: async () => ({ id: 2 }), delete: async () => { console.log('Deleting user...') await _.sleep(100) console.log('Deleted user.') }, },}
// Placeholder test functionconst executeTest = async () => { console.log('Executing test...') await _.sleep(100) console.log('Test complete.')}
await _.defer(async register => { const org = await api.org.create() register(async () => api.org.delete(org.id), { rethrow: true })
const user = await api.user.create() register(async () => api.user.delete(user.id), { rethrow: true })
await executeTest(org, user)})