• Stars
    star
    728
  • Rank 62,237 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 12 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Asynchronous function queue with adjustable concurrency
   ____  __  _____  __  _____
  / __ `/ / / / _ \/ / / / _ \
 / /_/ / /_/ /  __/ /_/ /  __/
 \__, /\__,_/\___/\__,_/\___/
   /_/

Asynchronous function queue with adjustable concurrency.

npm

This module exports a class Queue that implements most of the Array API. Pass async functions (ones that accept a callback or return a promise) to an instance's additive array methods. Processing begins when you call q.start().

Example

Do npm run example or npm run dev and open the example directory (and your console) to run the following program:

import Queue from 'queue'

const q = new Queue({ results: [] })

// add jobs using the familiar Array API
q.push(cb => {
  const result = 'two'
  cb(null, result)
})

q.push(
  cb => {
    const result = 'four'
    cb(null, result)
  },
  cb => {
    const result = 'five'
    cb(null, result)
  }
)

// jobs can accept a callback or return a promise
q.push(() => {
  return new Promise((resolve, reject) => {
    const result = 'one'
    resolve(result)
  })
})

q.unshift(cb => {
  const result = 'one'
  cb(null, result)
})

q.splice(2, 0, cb => {
  const result = 'three'
  cb(null, result)
})

// use the timeout feature to deal with jobs that
// take too long or forget to execute a callback
q.timeout = 100

q.addEventListener('timeout', e => {
  console.log('job timed out:', e.detail.job.toString().replace(/\n/g, ''))
  e.detail.next()
})

q.push(cb => {
  setTimeout(() => {
    console.log('slow job finished')
    cb()
  }, 200)
})

q.push(cb => {
  console.log('forgot to execute callback')
})

// jobs can also override the queue's timeout
// on a per-job basis
function extraSlowJob (cb) {
  setTimeout(() => {
    console.log('extra slow job finished')
    cb()
  }, 400)
}

extraSlowJob.timeout = 500
q.push(extraSlowJob)

// jobs can also opt-out of the timeout altogether
function superSlowJob (cb) {
  setTimeout(() => {
    console.log('super slow job finished')
    cb()
  }, 1000)
}

superSlowJob.timeout = null
q.push(superSlowJob)

// get notified when jobs complete
q.addEventListener('success', e => {
  console.log('job finished processing:', e.detail.toString().replace(/\n/g, ''))
  console.log('The result is:', e.detail.result)
})

// begin processing, get notified on end / failure
q.start(err => {
  if (err) throw err
  console.log('all done:', q.results)
})

Install

npm install queue

yarn add queue

Test

npm test

npm run dev // for testing in a browser, open test directory (and your console)

API

const q = new Queue([opts])

Constructor. opts may contain initial values for:

  • q.concurrency
  • q.timeout
  • q.autostart
  • q.results

Instance methods

q.start([cb])

Explicitly starts processing jobs and provides feedback to the caller when the queue empties or an error occurs. If cb is not passed a promise will be returned.

q.stop()

Stops the queue. can be resumed with q.start().

q.end([err])

Stop and empty the queue immediately.

Instance methods mixed in from Array

Mozilla has docs on how these methods work here. Note that slice does not copy the queue.

q.push(element1, ..., elementN)

q.unshift(element1, ..., elementN)

q.splice(index , howMany[, element1[, ...[, elementN]]])

q.pop()

q.shift()

q.slice(begin[, end])

q.reverse()

q.indexOf(searchElement[, fromIndex])

q.lastIndexOf(searchElement[, fromIndex])

Properties

q.concurrency

Max number of jobs the queue should process concurrently, defaults to Infinity.

q.timeout

Milliseconds to wait for a job to execute its callback. This can be overridden by specifying a timeout property on a per-job basis.

q.autostart

Ensures the queue is always running if jobs are available. Useful in situations where you are using a queue only for concurrency control.

q.results

An array to set job callback arguments on.

q.length

Jobs pending + jobs to process (readonly).

Events

q.dispatchEvent(new QueueEvent('start', { job }))

Immediately before a job begins to execute.

q.dispatchEvent(new QueueEvent('success', { result: [...result], job }))

After a job executes its callback.

q.dispatchEvent(new QueueEvent('error', { err, job }))

After a job passes an error to its callback.

q.dispatchEvent(new QueueEvent('timeout', { next, job }))

After q.timeout milliseconds have elapsed and a job has not executed its callback.

q.dispatchEvent(new QueueEvent('end', { err }))

After all jobs have been processed

Releases

The latest stable release is published to npm. Abbreviated changelog below:

  • 7.0
    • Modernized codebase, added new maintainer (@MaksimLavrenyuk)
  • 6.0
    • Add start event before job begins (@joelgriffith)
    • Add timeout property on a job to override the queue's timeout (@joelgriffith)
  • 5.0
    • Updated TypeScript bindings (@Codex-)
  • 4.4
    • Add results feature
  • 4.3
    • Add promise support (@kwolfy)
  • 4.2
    • Unref timers on end
  • 4.1
    • Add autostart feature
  • 4.0
    • Change license to MIT
  • 3.1.x
    • Add .npmignore
  • 3.0.x
    • Change the default concurrency to Infinity
    • Allow q.start() to accept an optional callback executed on q.emit('end')
  • 2.x
    • Major api changes / not backwards compatible with 1.x
  • 1.x
    • Early prototype

License

MIT

More Repositories

1

unicodes

Browse all of the unicodes
JavaScript
55
star
2

underpass

An efficient, secure localtunnel clone
JavaScript
10
star
3

multiparser

a streams2 compatible multipart-form parser
JavaScript
9
star
4

localstorage-fs

node's fs module for the browser backed by localStorage
JavaScript
7
star
5

level-sub

minimalist level-sublevel implementation
JavaScript
6
star
6

hex-transcoder

Fast hex / binary transcoding in pure JavaScript
JavaScript
6
star
7

is-tls-client-hello

Determine if a buffer contains a valid TLS ClientHello
JavaScript
5
star
8

eth-scripts

Javascript utilities for working with Ethereum
JavaScript
5
star
9

hyperbind

Create or update DOM elements by mapping query selectors to hypertext, plain text, attributes, classes, properties, other elements or lists.
JavaScript
5
star
10

shell-source

Source environment variables from a shell script into a Node.js process.
JavaScript
5
star
11

vpkg

a version oriented package manager
Shell
4
star
12

rpc-engine

Minimalist RPC library
JavaScript
3
star
13

splicer

A TCP proxy
JavaScript
3
star
14

random-ip

generate random ip(v4 or v6) addresses
JavaScript
3
star
15

unicode-blocks

An array of all the Unicode blocks
JavaScript
3
star
16

thru

minimalist transform stream implementation
JavaScript
3
star
17

url-state

Minimalist history API abstraction for building URL driven browser applications
JavaScript
3
star
18

unicode-database-parser

Parses individual lines from UnicodeData.txt
JavaScript
3
star
19

3d

cannon.js + regl + matrix3d
JavaScript
3
star
20

chromium

Open-source project behind Google Chrome https://www.chromium.org/
2
star
21

xevents

Use DOM events everywhere
JavaScript
2
star
22

ubuntu-init

cloud-init script for Ubuntu Server 12.04 Precise
Shell
2
star
23

lazy-scroll

A web component based on iOS's UITableView
JavaScript
2
star
24

pseudonet

A network modeling tool
JavaScript
2
star
25

tap-esm

TAP for es modules
JavaScript
2
star
26

terminal-stream

A stream for use at the terminals of circular pipelines
JavaScript
2
star
27

app-server

Personal flavor of static file http server
JavaScript
1
star
28

array-buffer-concat

Concatenate Array Buffers
JavaScript
1
star
29

cui

GUIs for the command line
JavaScript
1
star
30

hyperbase

A general purpose storage interface
JavaScript
1
star
31

realtime-model

firebase compatible model abstraction
JavaScript
1
star
32

wafers

Named file system wafer stack trees
Shell
1
star
33

neo4j-cypher

A Neo4j driver for making Cypher queries over HTTP
CoffeeScript
1
star
34

2502

An http server template that bundles the IBGateway java application
Python
1
star
35

dao

Minimal OpenZeppelin distributed autonomous organization demo
JavaScript
1
star
36

deferred

JavaScript
1
star
37

udp-ws

UDP <> WebSocket bridge with PSK auth
JavaScript
1
star
38

autopilot-remote

Remote control for Raymarine autopilots
JavaScript
1
star
39

contractor

User interface for any EVM smart contract you have an ABI for
JavaScript
1
star
40

dev

Personal flavor of dev / watch script
JavaScript
1
star
41

utf8-transcoder

Transcode JavaScript strings <> UTF-8 byte arrays
JavaScript
1
star
42

wallet-connect

WalletConnect 1.0 implementation using browser crypto
JavaScript
1
star
43

mikroapi

Minimalist Mikrotik API client
JavaScript
1
star
44

scene-2d

Multitouch capable 2d scene implementing pan, zoom and object selection
JavaScript
1
star
45

autocert

Get a TLS options object that will automagically certify your domains
JavaScript
1
star
46

loft

Loft a regular polygon with n sides between two points in 3d space
JavaScript
1
star
47

marauder

Marauder net visualization
JavaScript
1
star
48

contentful-db

Contentful database downloader / parser for use in the browser
JavaScript
1
star
49

registrar

A digital signature based identity memorization, recognition and administration protocol
JavaScript
1
star
50

scroll-refractor

A web component that scrolls its content perpendicularly
JavaScript
1
star
51

auth

Ideas for simpler authentication
JavaScript
1
star
52

fsdb

Human-friendly databases made with files and folders.
JavaScript
1
star
53

ca

Notes on how to set up a certificate authority
1
star
54

Keyboard

Keyboard as an object in the DOM
JavaScript
1
star
55

backbone-ext

Assorted backbone plugins and monkey patches
CoffeeScript
1
star