asynchronous-queue
One liner minimal (only 159 bytes) asynchronous function queue for node.js, browser and TypeScript
Install
npm install asynchronous-queue
Usage
Execute functions sequencially
The callback function passed into queue.push()
will always be executed sequencially, which means that the next callback function will wait until completion of former callback if any promise is returned.
// wait 300ms, then log '1', '2', and wait 200ms, then log '3', '4'queue.pushwait300.then queue.push queue.push queue.push
Handle promise completion
queue.push()
itself also returns a Promise to handle the completion of its callback function.
The returned Promise will be resolved right after the completion of the Promise which is returned from callback function.
// log 'start', then wait 500(300+200)ms, then log 'end' start
Chaining
If callback function returns a value, it will be the resolved value of the Promise returned from queue.push()
itself and also will be passed to the next callback function.
Optionally, createAsyncQueue()
accepts the value to pass to the very first callback function as its argument.
// log '1st', log '1st2nd', and log '1st2nd3rd' start
Error handling
It is important to handle possible rejections properly at the time the callback function is pushing to the queue because queue.push()
will implicitly handle rejections by adding .catch
block to prevent all of following callback functions from being rejected.
This means that any UnhandledPromiseRejection
will never be thrown even if the Promise returned from callback rejected without any handling.
To handle rejections on-the-fly, simply add .catch
block for the Promise from queue.push()
or use try await ~ catch
clause.
start
Typing
For safely typed chaining, type of the argument and return value can be specified optionally.
// queue.push() accepts any type of function queue.pushtruequeue.pushtrue // typed.push() only accepts function typed as (value: string) => string// then very first argument value must be specified typed.pusharg + '2nd'typed.pusharg + '3rd'