4.0.1 • Published 4 months ago

@escapace/sequentialize v4.0.1

Weekly downloads
-
License
MPL-2.0
Repository
github
Last release
4 months ago

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()

// Original async function
const fetchData = async (id: string) => {
  const response = await fetch(`/api/data/${id}`)
  return response.json()
}

// Wrapped function executes sequentially
const sequentialFetch = wrapper(fetchData)

// These calls will execute one after another, not concurrently
void sequentialFetch('1') // executes first
void sequentialFetch('2') // waits for first to complete
void sequentialFetch('3') // waits for second to complete

How it works

The sequentialize function returns a wrapper that maintains an internal queue of promises. Each wrapped function call:

  1. Waits for all previous calls to complete
  2. Executes the original function
  3. Resolves its promise
  4. 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')) // does not catch
void mayFail(true).catch(() => console.log('Call 2 failed')) // logs "Call 2 failed"
void mayFail(false).catch(() => console.log('Call 3 failed')) // logs "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
3.0.0

10 months ago

4.0.1

4 months ago

4.0.0

8 months ago

2.1.4

2 years ago

2.1.2

3 years ago

2.1.1

3 years ago

2.1.3

2 years ago

2.1.0

3 years ago

2.0.0

3 years ago

1.3.10

4 years ago

1.3.11

4 years ago

1.3.12

4 years ago

1.3.9

5 years ago

1.3.8

5 years ago

1.3.7

5 years ago

1.3.6

5 years ago

1.3.5

5 years ago

1.3.4

5 years ago

1.3.3

5 years ago

1.3.2

5 years ago

1.3.1

5 years ago

1.3.0

5 years ago

1.2.0

7 years ago

1.1.0

7 years ago