A simple Promise based queue, that allows you to push(enqueue) actions and wait till it gets to their turn before resolving or also wait for the entire queue to be empty before resolving.
Queue up idempotent operations that can run simultaneously and return the same value even when there's a dependency that can cause the operation to return different value. For example, you can queue up all calls to find or create an entity if not available, if available return the value. If the call is run simultaneously, we might end up with a lot of created entities. With Queue, you can add any call to the queue, so they are waiting for the first find or create operation to be done before returning the entity. see unique user id test
yarn add push-and-wait-queue
npm install push-and-wait-queue
Browser, you can use UNPKG or JSDelivr
<script src="https://cdn.jsdelivr.net/npm/push-and-wait-queue@latest/build/index.min.js"></script>
const queue = new PushAndWaitQueue();
import PushAndWaitQueue from "push-and-wait-queue";
const queue = new PushAndWaitQueue();
queue.push(task: ITask);
interface ITask<T> {
action: ()=>Promise<T>
onDone?: (err: Error|undefined, result?: T)=>void
}
Task fields | Description |
---|---|
action |
required a function that returns a Promise |
onDone |
optional a function that handles either the result or error from action promise |
see tests
import PushAndWaitQueue from "push-and-wait-queue";
const queue = new PushAndWaitQueue();
const valueFromTask1;
const task1 = {
action: async () => {
// long running process
// return value
return "3000 entities";
},
onDone: (err, resultOfAction) => {
valueFromTask1 = resultOfAction;
},
};
const task2 = {
action: async () => {
// use value from last tasks
return `with value is ${valueFromTask1}`;
},
onDone: (err, resultOfAction) => {
console.log(resultOfAction);
},
};
queue.push(task1).then(() => {});
queue.push(task2).then(() => {});
You can wait at any time for a queue to be done or idle via .push(...).then
since it returns a running instance of the queue
...
const onQueueCompleted = () => {
console.log('queue is idle/completed')
}
queue.push(...).then(onQueueCompleted)
Clone repo and run
yarn install
Every PR title or at least one commit must follow conventional commit message pattern.
Start the library build and test in watch mode for every file edit.
Build distribution bundle to ./build/
directory.
Lints and test library.
Uses ts-standard for linting so you don't have to worry about ESLint configurations
Automatically fixes any lint errors encountered.
Run build script in watch mode.