sequentialize
Wrap async functions to queue multiple calls for sequential execution.
Installation
pnpm add @escapace/sequentialize
Usage
import { sequentialize } from '@escapace/sequentialize'
const wrapper = sequentialize()
const fetchData = async (id: string) => {
const response = await fetch(`/api/data/${id}`)
return response.json()
}
const sequentialFetch = wrapper(fetchData)
void sequentialFetch('1')
void sequentialFetch('2')
void sequentialFetch('3')
How it works
The sequentialize function returns a wrapper that maintains an internal queue of promises. Each wrapped function call:
- Waits for all previous calls to complete
- Executes the original function
- Resolves its promise
- Allows the next queued call to proceed
Functions execute in first-in-first-out (FIFO) order regardless of their individual completion times.
Error handling
When a sequentialized function fails, all subsequent functions in the queue will fail with the same error due to the promise chain dependency:
const wrapper = sequentialize()
const mayFail = wrapper(async (shouldFail: boolean) => {
if (shouldFail) throw new Error('Failed')
return 'Success'
})
void mayFail(false).catch(() => console.log('Call 1 failed'))
void mayFail(true).catch(() => console.log('Call 2 failed'))
void mayFail(false).catch(() => console.log('Call 3 failed'))
API
sequentialize()
Returns a wrapper function that converts async functions to sequential execution.
Returns: <T>(fn: T) => T - A function that wraps async functions
Deferred
A promise wrapper with manual resolution control. Used internally by sequentialize.
Methods:
resolve(value?: T | PromiseLike<T>) - Resolve the promise
reject(reason?: any) - Reject the promise
isPending() - Check if promise is pending
isFulfilled() - Check if promise fulfilled successfully
isRejected() - Check if promise was rejected
isResolved() - Check if promise has been resolved (fulfilled or rejected)
Properties:
promise: Promise<T> - The underlying promise