A tiny utility that simulates a "microtask-like" queue for running callbacks immediately after the current function body completes, using a RemovableQueue.
npm install post-immediateimport { 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 - deferredCallbacks can schedule additional callbacks:
withPostImmediate((postImmediate) => {
postImmediate(() => {
console.log("A");
postImmediate(() => console.log("C"));
});
postImmediate(() => console.log("B"));
});fn– A function that receivespostImmediate, which you call to enqueue callbacks.- The queue is drained after
fncompletes, running all posted callbacks in FIFO order.
- All synchronous code in
fnruns first. - After
fnreturns, all callbacks posted viapostImmediateare executed in the order they were added. - Callbacks that post more callbacks are processed until the queue is empty.
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.
MIT