Skip to content

wopjs/async-seq

Repository files navigation

@wopjs/async-seq

Docs Build Status Coverage Status

npm-version minified-size no-dependencies tree-shakable side-effect-free

Run async functions one-by-one in a sequence.

Docs: https://wopjs.github.io/async-seq/

Install

npm add @wopjs/async-seq

Examples

import { seq } from "@wopjs/async-seq";

const s = seq();

// add async functions to the sequence and wait for the sequence to finish
await s.add(
  () => {
    const ticket = setTimeout(spy, 100);
    return () => clearTimeout(ticket);
  },
  async () => {
    const data = await fetch("https://example.com").then(r => r.json());
    console.log(data);
  }
);

// or manually wait for the sequence to finish
await s.wait();

// cancel all tasks
s.dispose();

By default the sequence has unlimited size. You can limit the size of the sequence by passing the window option. Together with the dropHead option you can control the behavior of the sequence when it reaches its limit.

Simulate debounce:

const debounce = (task: () => void, ms: number) => {
  const s = seq({ window: 1, dropHead: true });
  return () =>
    s.add(() => {
      const ticket = setTimeout(task, ms);
      return () => clearTimeout(ticket);
    });
};

const debounced = debounce(() => console.log("task"), 100);

for (let i = 0; i < 10; i++) {
  debounced();
}

License

MIT @ wopjs