Skip to content

basic-examples/post-immediate

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

post-immediate

A tiny utility that simulates a "microtask-like" queue for running callbacks immediately after the current function body completes, using a RemovableQueue.

Installation

npm install post-immediate

Usage

import { withPostImmediate } from "post-immediate";

withPostImmediate((postImmediate) => {
  console.log("1 - sync");
  postImmediate(() => console.log("3 - deferred"));
  console.log("2 - sync");
});
// Output:
// 1 - sync
// 2 - sync
// 3 - deferred

Nested Posts

Callbacks can schedule additional callbacks:

withPostImmediate((postImmediate) => {
  postImmediate(() => {
    console.log("A");
    postImmediate(() => console.log("C"));
  });
  postImmediate(() => console.log("B"));
});

API

withPostImmediate(fn: (postImmediate: (fn: () => void) => void) => void): void

  • fn – A function that receives postImmediate, which you call to enqueue callbacks.
  • The queue is drained after fn completes, running all posted callbacks in FIFO order.

Behavior

  • All synchronous code in fn runs first.
  • After fn returns, all callbacks posted via postImmediate are executed in the order they were added.
  • Callbacks that post more callbacks are processed until the queue is empty.

Why?

This pattern is useful when you want predictable, synchronous-like batching of tasks without relying on setTimeout(fn) or Promise.resolve().then(fn) microtasks. It can be useful for custom event loops, scheduling, or controlled testing of async-like behavior.

License

MIT

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published