node package manager
We need your input. Help make JavaScript better: Take the 2017 JavaScript Ecosystem survey »

@coolgk/queue

@coolgk/queue

a javascript / typescript module

npm install @coolgk/queue

This is a super lightweight function that limits the number of async functions run concurrently and run them in order.

  1. Put async functions in a queue and limit the number of async functions that run concurrently.
  2. Run async functions in order
  3. Run x number of functions in parallel per batch in order. similar to async / await when the second parameter is 1.

Examples

import { queue } from '@coolgk/queue';
// OR
// const { queue } = require('@coolgk/queue');
 
function a (x) {
    console.log('start a');
    return new Promise((resolve) => setTimeout(() => { console.log('end a', x); resolve('a') }, 1300));
}
 
function b (x) {
    console.log('start b');
    return new Promise((resolve) => setTimeout(() => { console.log('end b', x); resolve('b') }, 1200));
}
 
function c (x) {
    console.log('start c');
    return new Promise((resolve) => setTimeout(() => { console.log('end c', x); resolve('c') }, 100));
}
 
// call a, b, c in order i.e. b does not start until a resolves
queue(a);
queue(b);
queue(c);
 
// call a 5 times, each waits until the previous call resolves
[1,2,3,4,5].forEach(() => {
    queue(a)
});
 
// run 3 jobs at a time
[1,2,3,4,5,6,7,8,9,10].forEach(() => {
    queue(a, 3)
});
 

queue(callback, [limit]) ⇒ promise

Kind: global function

Param Type Default Description
callback function callback function that returns a promise or any other types
[limit] number 1 number of callback to run at the same time, by default one callback at a time