├── .eslintrc
├── .gitignore
├── .npmignore
├── LICENSE
├── README.md
├── d3-queue.sublime-project
├── index.js
├── package.json
├── src
├── array.js
└── queue.js
└── test
├── abortableTask.js
├── asynchronousTask.js
├── deferredSynchronousTask.js
├── queue-test.js
└── synchronousTask.js
/.eslintrc:
--------------------------------------------------------------------------------
1 | parserOptions:
2 | sourceType: "module"
3 |
4 | env:
5 | es6: true
6 | browser: true
7 |
8 | extends:
9 | "eslint:recommended"
10 |
11 | rules:
12 | no-cond-assign: 0
13 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.sublime-workspace
2 | .DS_Store
3 | build/
4 | node_modules
5 | npm-debug.log
6 |
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | *.sublime-*
2 | build/*.zip
3 | test/
4 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (c) 2012-2016, Michael Bostock
2 | All rights reserved.
3 |
4 | Redistribution and use in source and binary forms, with or without
5 | modification, are permitted provided that the following conditions are met:
6 |
7 | * Redistributions of source code must retain the above copyright notice, this
8 | list of conditions and the following disclaimer.
9 |
10 | * Redistributions in binary form must reproduce the above copyright notice,
11 | this list of conditions and the following disclaimer in the documentation
12 | and/or other materials provided with the distribution.
13 |
14 | * The name Michael Bostock may not be used to endorse or promote products
15 | derived from this software without specific prior written permission.
16 |
17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20 | DISCLAIMED. IN NO EVENT SHALL MICHAEL BOSTOCK BE LIABLE FOR ANY DIRECT,
21 | INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
22 | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
24 | OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
25 | NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
26 | EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # d3-queue
2 |
3 | A **queue** evaluates zero or more *deferred* asynchronous tasks with configurable concurrency: you control how many tasks run at the same time. When all the tasks complete, or an error occurs, the queue passes the results to your *await* callback. This library is similar to [Async.js](https://github.com/caolan/async)’s [parallel](https://github.com/caolan/async#paralleltasks-callback) (when *concurrency* is infinite), [series](https://github.com/caolan/async#seriestasks-callback) (when *concurrency* is 1), and [queue](https://github.com/caolan/async#queue), but features a much smaller footprint: as of release 2, d3-queue is about 700 bytes gzipped, compared to 4,300 for Async.
4 |
5 | Each task is defined as a function that takes a callback as its last argument. For example, here’s a task that says hello after a short delay:
6 |
7 | ```js
8 | function delayedHello(callback) {
9 | setTimeout(function() {
10 | console.log("Hello!");
11 | callback(null);
12 | }, 250);
13 | }
14 | ```
15 |
16 | When a task completes, it must call the provided callback. The first argument to the callback should be null if the task is successful, or the error if the task failed. The optional second argument to the callback is the return value of the task. (To return multiple values from a single callback, wrap the results in an object or array.)
17 |
18 | To run multiple tasks simultaneously, create a queue, *defer* your tasks, and then register an *await* callback to be called when all of the tasks complete (or an error occurs):
19 |
20 | ```js
21 | var q = d3.queue();
22 | q.defer(delayedHello);
23 | q.defer(delayedHello);
24 | q.await(function(error) {
25 | if (error) throw error;
26 | console.log("Goodbye!");
27 | });
28 | ```
29 |
30 | Of course, you can also use a `for` loop to defer many tasks:
31 |
32 | ```js
33 | var q = d3.queue();
34 |
35 | for (var i = 0; i < 1000; ++i) {
36 | q.defer(delayedHello);
37 | }
38 |
39 | q.awaitAll(function(error) {
40 | if (error) throw error;
41 | console.log("Goodbye!");
42 | });
43 | ```
44 |
45 | Tasks can take optional arguments. For example, here’s how to configure the delay before hello and provide a name:
46 |
47 | ```js
48 | function delayedHello(name, delay, callback) {
49 | setTimeout(function() {
50 | console.log("Hello, " + name + "!");
51 | callback(null);
52 | }, delay);
53 | }
54 | ```
55 |
56 | Any additional arguments provided to [*queue*.defer](#queue_defer) are automatically passed along to the task function before the callback argument. You can also use method chaining for conciseness, avoiding the need for a local variable:
57 |
58 | ```js
59 | d3.queue()
60 | .defer(delayedHello, "Alice", 250)
61 | .defer(delayedHello, "Bob", 500)
62 | .defer(delayedHello, "Carol", 750)
63 | .await(function(error) {
64 | if (error) throw error;
65 | console.log("Goodbye!");
66 | });
67 | ```
68 |
69 | The [asynchronous callback pattern](https://github.com/maxogden/art-of-node#callbacks) is very common in Node.js, so Queue works directly with many Node APIs. For example, to [stat two files](https://nodejs.org/dist/latest/docs/api/fs.html#fs_fs_stat_path_callback) concurrently:
70 |
71 | ```js
72 | d3.queue()
73 | .defer(fs.stat, __dirname + "/../Makefile")
74 | .defer(fs.stat, __dirname + "/../package.json")
75 | .await(function(error, file1, file2) {
76 | if (error) throw error;
77 | console.log(file1, file2);
78 | });
79 | ```
80 |
81 | You can also make abortable tasks: these tasks return an object with an *abort* method which terminates the task. So, if a task calls [setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout) on start, it can call [clearTimeout](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearTimeout) on abort. For example:
82 |
83 | ```js
84 | function delayedHello(name, delay, callback) {
85 | var id = setTimeout(function() {
86 | console.log("Hello, " + name + "!");
87 | callback(null);
88 | }, delay);
89 | return {
90 | abort: function() {
91 | clearTimeout(id);
92 | }
93 | };
94 | }
95 | ```
96 |
97 | When you call [*queue*.abort](#queue_abort), any in-progress tasks will be immediately aborted; in addition, any pending (not-yet-started) tasks will not be started. Note that you can also use *queue*.abort *without* abortable tasks, in which case pending tasks will be cancelled, though active tasks will continue to run. Conveniently, the [d3-request](https://github.com/d3/d3-request) library implements abort atop XMLHttpRequest. For example:
98 |
99 | ```js
100 | var q = d3.queue()
101 | .defer(d3.request, "http://www.google.com:81")
102 | .defer(d3.request, "http://www.google.com:81")
103 | .defer(d3.request, "http://www.google.com:81")
104 | .awaitAll(function(error, results) {
105 | if (error) throw error;
106 | console.log(results);
107 | });
108 | ```
109 |
110 | To abort these requests, call `q.abort()`.
111 |
112 | ## Installing
113 |
114 | If you use NPM, `npm install d3-queue`. If you use Bower, `bower install d3-queue`. Otherwise, download the [latest release](https://github.com/d3/d3-queue/releases/latest). You can also load directly from [d3js.org](https://d3js.org), either as a [standalone library](https://d3js.org/d3-queue.v3.min.js) or as part of [D3 4.0](https://github.com/d3/d3). AMD, CommonJS, and vanilla environments are supported. In vanilla, a `d3` global is exported:
115 |
116 | ```html
117 |
118 |
123 | ```
124 |
125 | [Try d3-queue in your browser.](https://tonicdev.com/npm/d3-queue)
126 |
127 | ## API Reference
128 |
129 | # d3.queue([concurrency]) [<>](https://github.com/d3/d3-queue/blob/master/src/queue.js "Source")
130 |
131 | Constructs a new queue with the specified *concurrency*. If *concurrency* is not specified, the queue has infinite concurrency. Otherwise, *concurrency* is a positive integer. For example, if *concurrency* is 1, then all tasks will be run in series. If *concurrency* is 3, then at most three tasks will be allowed to proceed concurrently; this is useful, for example, when loading resources in a web browser.
132 |
133 | # queue.defer(task[, arguments…]) [<>](https://github.com/d3/d3-queue/blob/master/src/queue.js#L20 "Source")
134 |
135 | Adds the specified asynchronous *task* callback to the queue, with any optional *arguments*. The *task* is a function that will be called when the task should start. It is passed the specified optional *arguments* and an additional *callback* as the last argument; the callback must be invoked by the task when it finishes. The task must invoke the callback with two arguments: the *error*, if any, and the *result* of the task. To return multiple results from a single callback, wrap the results in an object or array.
136 |
137 | For example, here’s a task which computes the answer to the ultimate question of life, the universe, and everything after a short delay:
138 |
139 | ```js
140 | function simpleTask(callback) {
141 | setTimeout(function() {
142 | callback(null, {answer: 42});
143 | }, 250);
144 | }
145 | ```
146 |
147 | If the task calls back with an error, any tasks that were scheduled *but not yet started* will not run. For a serial queue (of *concurrency* 1), this means that a task will only run if all previous tasks succeed. For a queue with higher concurrency, only the first error that occurs is reported to the await callback, and tasks that were started before the error occurred will continue to run; note, however, that their results will not be reported to the await callback.
148 |
149 | Tasks can only be deferred before [*queue*.await](#queue_await) or [*queue*.awaitAll](#queue_awaitAll) is called. If a task is deferred after then, an error is thrown. If the *task* is not a function, an error is thrown.
150 |
151 | # queue.abort() [<>](https://github.com/d3/d3-queue/blob/master/src/queue.js#L29 "Source")
152 |
153 | Aborts any active tasks, invoking each active task’s *task*.abort function, if any. Also prevents any new tasks from starting, and immediately invokes the [*queue*.await](#queue_await) or [*queue*.awaitAll](#queue_awaitAll) callback with an error indicating that the queue was aborted. See the [introduction](#d3-queue) for an example implementation of an abortable task. Note that if your tasks are not abortable, any running tasks will continue to run, even after the await callback has been invoked with the abort error. The await callback is invoked exactly once on abort, and so is not called when any running tasks subsequently succeed or fail.
154 |
155 | # queue.await(callback) [<>](https://github.com/d3/d3-queue/blob/master/src/queue.js#L33 "Source")
156 |
157 | Sets the *callback* to be invoked when all deferred tasks have finished. The first argument to the *callback* is the first error that occurred, or null if no error occurred. If an error occurred, there are no additional arguments to the callback. Otherwise, the *callback* is passed each result as an additional argument. For example:
158 |
159 | ```js
160 | d3.queue()
161 | .defer(fs.stat, __dirname + "/../Makefile")
162 | .defer(fs.stat, __dirname + "/../package.json")
163 | .await(function(error, file1, file2) { console.log(file1, file2); });
164 | ```
165 |
166 | If all [deferred](#queue_defer) tasks have already completed, the callback will be invoked immediately. This method may only be called once, after any tasks have been deferred. If this method is called multiple times, or if it is called after [*queue*.awaitAll](#queue_awaitAll), an error is thrown. If the *callback* is not a function, an error is thrown.
167 |
168 | # queue.awaitAll(callback) [<>](https://github.com/d3/d3-queue/blob/master/src/queue.js#L39 "Source")
169 |
170 | Sets the *callback* to be invoked when all deferred tasks have finished. The first argument to the *callback* is the first error that occurred, or null if no error occurred. If an error occurred, there are no additional arguments to the callback. Otherwise, the *callback* is also passed an array of results as the second argument. For example:
171 |
172 | ```js
173 | d3.queue()
174 | .defer(fs.stat, __dirname + "/../Makefile")
175 | .defer(fs.stat, __dirname + "/../package.json")
176 | .awaitAll(function(error, files) { console.log(files); });
177 | ```
178 |
179 | If all [deferred](#queue_defer) tasks have already completed, the callback will be invoked immediately. This method may only be called once, after any tasks have been deferred. If this method is called multiple times, or if it is called after [*queue*.await](#queue_await), an error is thrown. If the *callback* is not a function, an error is thrown.
180 |
--------------------------------------------------------------------------------
/d3-queue.sublime-project:
--------------------------------------------------------------------------------
1 | {
2 | "folders": [
3 | {
4 | "path": ".",
5 | "file_exclude_patterns": [
6 | "*.sublime-workspace"
7 | ],
8 | "folder_exclude_patterns": [
9 | "build"
10 | ]
11 | }
12 | ]
13 | }
14 |
--------------------------------------------------------------------------------
/index.js:
--------------------------------------------------------------------------------
1 | export {default as queue} from "./src/queue";
2 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "d3-queue",
3 | "version": "3.0.7",
4 | "description": "Evaluate asynchronous tasks with configurable concurrency.",
5 | "keywords": [
6 | "d3",
7 | "d3-module",
8 | "asynchronous",
9 | "async",
10 | "queue"
11 | ],
12 | "homepage": "https://d3js.org/d3-queue/",
13 | "license": "BSD-3-Clause",
14 | "author": {
15 | "name": "Mike Bostock",
16 | "url": "http://bost.ocks.org/mike"
17 | },
18 | "main": "build/d3-queue.js",
19 | "module": "index",
20 | "jsnext:main": "index",
21 | "repository": {
22 | "type": "git",
23 | "url": "https://github.com/d3/d3-queue.git"
24 | },
25 | "scripts": {
26 | "pretest": "rm -rf build && mkdir build && rollup --banner \"$(preamble)\" -f umd -n d3 -o build/d3-queue.js -- index.js",
27 | "test": "tape 'test/**/*-test.js' && eslint index.js src",
28 | "prepublish": "npm run test && uglifyjs --preamble \"$(preamble)\" build/d3-queue.js -c -m -o build/d3-queue.min.js",
29 | "postpublish": "git push && git push --tags && cd ../d3-queue-bower && git pull && cp -v ../d3-queue/README.md ../d3-queue/LICENSE ../d3-queue/build/d3-queue.js . && git add README.md LICENSE d3-queue.js && git commit -m ${npm_package_version} && git tag -am ${npm_package_version} v${npm_package_version} && git push && git push --tags && cd ../d3.github.com && git pull && cp ../d3-queue/build/d3-queue.js d3-queue.v3.js && cp ../d3-queue/build/d3-queue.min.js d3-queue.v3.min.js && git add d3-queue.v3.js d3-queue.v3.min.js && git commit -m \"d3-queue ${npm_package_version}\" && git push && cd ../d3-queue && zip -j build/d3-queue.zip -- LICENSE README.md build/d3-queue.js build/d3-queue.min.js"
30 | },
31 | "devDependencies": {
32 | "eslint": "3",
33 | "package-preamble": "0.1",
34 | "rollup": "0.41",
35 | "tape": "4",
36 | "uglify-js": "^2.8.11"
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/array.js:
--------------------------------------------------------------------------------
1 | export var slice = [].slice;
2 |
--------------------------------------------------------------------------------
/src/queue.js:
--------------------------------------------------------------------------------
1 | import {slice} from "./array";
2 |
3 | var noabort = {};
4 |
5 | function Queue(size) {
6 | this._size = size;
7 | this._call =
8 | this._error = null;
9 | this._tasks = [];
10 | this._data = [];
11 | this._waiting =
12 | this._active =
13 | this._ended =
14 | this._start = 0; // inside a synchronous task callback?
15 | }
16 |
17 | Queue.prototype = queue.prototype = {
18 | constructor: Queue,
19 | defer: function(callback) {
20 | if (typeof callback !== "function") throw new Error("invalid callback");
21 | if (this._call) throw new Error("defer after await");
22 | if (this._error != null) return this;
23 | var t = slice.call(arguments, 1);
24 | t.push(callback);
25 | ++this._waiting, this._tasks.push(t);
26 | poke(this);
27 | return this;
28 | },
29 | abort: function() {
30 | if (this._error == null) abort(this, new Error("abort"));
31 | return this;
32 | },
33 | await: function(callback) {
34 | if (typeof callback !== "function") throw new Error("invalid callback");
35 | if (this._call) throw new Error("multiple await");
36 | this._call = function(error, results) { callback.apply(null, [error].concat(results)); };
37 | maybeNotify(this);
38 | return this;
39 | },
40 | awaitAll: function(callback) {
41 | if (typeof callback !== "function") throw new Error("invalid callback");
42 | if (this._call) throw new Error("multiple await");
43 | this._call = callback;
44 | maybeNotify(this);
45 | return this;
46 | }
47 | };
48 |
49 | function poke(q) {
50 | if (!q._start) {
51 | try { start(q); } // let the current task complete
52 | catch (e) {
53 | if (q._tasks[q._ended + q._active - 1]) abort(q, e); // task errored synchronously
54 | else if (!q._data) throw e; // await callback errored synchronously
55 | }
56 | }
57 | }
58 |
59 | function start(q) {
60 | while (q._start = q._waiting && q._active < q._size) {
61 | var i = q._ended + q._active,
62 | t = q._tasks[i],
63 | j = t.length - 1,
64 | c = t[j];
65 | t[j] = end(q, i);
66 | --q._waiting, ++q._active;
67 | t = c.apply(null, t);
68 | if (!q._tasks[i]) continue; // task finished synchronously
69 | q._tasks[i] = t || noabort;
70 | }
71 | }
72 |
73 | function end(q, i) {
74 | return function(e, r) {
75 | if (!q._tasks[i]) return; // ignore multiple callbacks
76 | --q._active, ++q._ended;
77 | q._tasks[i] = null;
78 | if (q._error != null) return; // ignore secondary errors
79 | if (e != null) {
80 | abort(q, e);
81 | } else {
82 | q._data[i] = r;
83 | if (q._waiting) poke(q);
84 | else maybeNotify(q);
85 | }
86 | };
87 | }
88 |
89 | function abort(q, e) {
90 | var i = q._tasks.length, t;
91 | q._error = e; // ignore active callbacks
92 | q._data = undefined; // allow gc
93 | q._waiting = NaN; // prevent starting
94 |
95 | while (--i >= 0) {
96 | if (t = q._tasks[i]) {
97 | q._tasks[i] = null;
98 | if (t.abort) {
99 | try { t.abort(); }
100 | catch (e) { /* ignore */ }
101 | }
102 | }
103 | }
104 |
105 | q._active = NaN; // allow notification
106 | maybeNotify(q);
107 | }
108 |
109 | function maybeNotify(q) {
110 | if (!q._active && q._call) {
111 | var d = q._data;
112 | q._data = undefined; // allow gc
113 | q._call(q._error, d);
114 | }
115 | }
116 |
117 | export default function queue(concurrency) {
118 | if (concurrency == null) concurrency = Infinity;
119 | else if (!((concurrency = +concurrency) >= 1)) throw new Error("invalid concurrency");
120 | return new Queue(concurrency);
121 | }
122 |
--------------------------------------------------------------------------------
/test/abortableTask.js:
--------------------------------------------------------------------------------
1 | module.exports = function(delay) {
2 | var active = 0,
3 | counter = {scheduled: 0, aborted: 0};
4 |
5 | function task(callback) {
6 | var index = counter.scheduled++;
7 | ++active;
8 | var timeout = setTimeout(function() {
9 | timeout = null;
10 | try {
11 | callback(null, {active: active, index: index});
12 | } finally {
13 | --active;
14 | }
15 | }, delay);
16 | return {
17 | abort: function() {
18 | if (timeout) {
19 | timeout = clearTimeout(timeout);
20 | ++counter.aborted;
21 | }
22 | }
23 | };
24 | }
25 |
26 | task.aborted = function() {
27 | return counter.aborted;
28 | };
29 |
30 | return task;
31 | };
32 |
--------------------------------------------------------------------------------
/test/asynchronousTask.js:
--------------------------------------------------------------------------------
1 | module.exports = function(counter) {
2 | var active = 0;
3 |
4 | if (!counter) counter = {scheduled: 0};
5 |
6 | return function(callback) {
7 | var index = counter.scheduled++;
8 | ++active;
9 | process.nextTick(function() {
10 | try {
11 | callback(null, {active: active, index: index});
12 | } finally {
13 | --active;
14 | }
15 | });
16 | };
17 | }
18 |
--------------------------------------------------------------------------------
/test/deferredSynchronousTask.js:
--------------------------------------------------------------------------------
1 | module.exports = function(counter) {
2 | var active = 0, deferrals = [];
3 |
4 | if (!counter) counter = {scheduled: 0};
5 |
6 | function task(callback) {
7 | if (deferrals) return deferrals.push({callback: callback, index: counter.scheduled++});
8 | try {
9 | callback(null, {active: ++active, index: counter.scheduled++});
10 | } finally {
11 | --active;
12 | }
13 | }
14 |
15 | task.finish = function() {
16 | var deferrals_ = deferrals.slice();
17 | deferrals = null;
18 | deferrals_.forEach(function(deferral) {
19 | try {
20 | deferral.callback(null, {active: ++active, index: deferral.index});
21 | } finally {
22 | --active;
23 | }
24 | });
25 | };
26 |
27 | return task;
28 | };
29 |
--------------------------------------------------------------------------------
/test/queue-test.js:
--------------------------------------------------------------------------------
1 | var fs = require("fs"),
2 | tape = require("tape"),
3 | abortableTask = require("./abortableTask"),
4 | asynchronousTask = require("./asynchronousTask"),
5 | deferredSynchronousTask = require("./deferredSynchronousTask"),
6 | synchronousTask = require("./synchronousTask"),
7 | queue = require("../");
8 |
9 | tape("example queue of fs.stat", function(test) {
10 | queue.queue()
11 | .defer(fs.stat, __dirname + "/../index.js")
12 | .defer(fs.stat, __dirname + "/../README.md")
13 | .defer(fs.stat, __dirname + "/../package.json")
14 | .await(callback);
15 |
16 | function callback(error, one, two, three) {
17 | test.equal(error, null);
18 | test.ok(one.size > 0);
19 | test.ok(two.size > 0);
20 | test.ok(three.size > 0);
21 | test.end();
22 | }
23 | });
24 |
25 | tape("if the concurrency is invalid, an Error is thrown", function(test) {
26 | test.throws(function() { queue.queue(NaN); }, /Error/);
27 | test.throws(function() { queue.queue(0); }, /Error/);
28 | test.throws(function() { queue.queue(-1); }, /Error/);
29 | test.end();
30 | });
31 |
32 | tape("queue.defer throws an error if passed a non-function", function(test) {
33 | test.throws(function() { queue.queue().defer(42); }, /Error/);
34 | test.end();
35 | });
36 |
37 | tape("queue.await throws an error if passed a non-function", function(test) {
38 | var task = asynchronousTask();
39 | test.throws(function() { queue.queue().defer(task).await(42); }, /Error/);
40 | test.end();
41 | });
42 |
43 | tape("queue.awaitAll throws an error if passed a non-function", function(test) {
44 | var task = asynchronousTask();
45 | test.throws(function() { queue.queue().defer(task).awaitAll(42); }, /Error/);
46 | test.end();
47 | });
48 |
49 | tape("in a queue of a single synchronous task that errors, the error is returned", function(test) {
50 | queue.queue()
51 | .defer(function(callback) { callback(-1); })
52 | .await(callback);
53 |
54 | function callback(error, result) {
55 | test.equal(error, -1);
56 | test.equal(result, undefined);
57 | test.end();
58 | }
59 | });
60 |
61 | tape("in a queue of a single asynchronous task that errors, the error is returned", function(test) {
62 | queue.queue()
63 | .defer(function(callback) { process.nextTick(function() { callback(-1); }); })
64 | .await(callback);
65 |
66 | function callback(error, result) {
67 | test.equal(error, -1);
68 | test.equal(result, undefined);
69 | test.end();
70 | }
71 | });
72 |
73 | tape("in a queue with multiple tasks that error, the first error is returned", function(test) {
74 | queue.queue()
75 | .defer(function(callback) { setTimeout(function() { callback(-2); }, 100); })
76 | .defer(function(callback) { process.nextTick(function() { callback(-1); }); })
77 | .defer(function(callback) { setTimeout(function() { callback(-3); }, 200); })
78 | .await(callback);
79 |
80 | function callback(error, one, two, three) {
81 | test.equal(error, -1);
82 | test.equal(one, undefined);
83 | test.equal(two, undefined);
84 | test.equal(three, undefined);
85 | test.end();
86 | }
87 | });
88 |
89 | tape("in a queue with multiple tasks where one errors, the first error is returned", function(test) {
90 | queue.queue()
91 | .defer(function(callback) { process.nextTick(function() { callback(-1); }); })
92 | .defer(function(callback) { process.nextTick(function() { callback(null, 'ok'); }); })
93 | .await(callback);
94 |
95 | function callback(error, one, two) {
96 | test.equal(error, -1);
97 | test.equal(one, undefined);
98 | test.equal(two, undefined);
99 | test.end();
100 | }
101 | });
102 |
103 | tape("in a queue with multiple synchronous tasks that error, the first error prevents the other tasks from running", function(test) {
104 | queue.queue()
105 | .defer(function(callback) { callback(-1); })
106 | .defer(function(callback) { callback(-2); })
107 | .defer(function(callback) { throw new Error; })
108 | .await(callback);
109 |
110 | function callback(error, one, two, three) {
111 | test.equal(error, -1);
112 | test.equal(one, undefined);
113 | test.equal(two, undefined);
114 | test.equal(three, undefined);
115 | test.end();
116 | }
117 | });
118 |
119 | tape("in a queue with a task that throws an error synchronously, the error is reported to the await callback", function(test) {
120 | queue.queue()
121 | .defer(function(callback) { throw new Error("foo"); })
122 | .await(callback);
123 |
124 | function callback(error) {
125 | test.equal(error.message, "foo");
126 | test.end();
127 | }
128 | });
129 |
130 | tape("in a queue with a task that throws an error after calling back, the error is ignored", function(test) {
131 | queue.queue()
132 | .defer(function(callback) { setTimeout(function() { callback(null, 1); }, 100); })
133 | .defer(function(callback) { callback(null, 2); process.nextTick(function() { callback(new Error("foo")); }); })
134 | .await(callback);
135 |
136 | function callback(error, one, two) {
137 | test.equal(error, null);
138 | test.equal(one, 1);
139 | test.equal(two, 2);
140 | test.end();
141 | }
142 | });
143 |
144 | tape("in a queue with a task that doesn’t terminate and another that errors synchronously, the error is still reported", function(test) {
145 | queue.queue()
146 | .defer(function() { /* Run forever! */ })
147 | .defer(function(callback) { callback(new Error("foo")); })
148 | .await(callback);
149 |
150 | function callback(error) {
151 | test.equal(error.message, "foo");
152 | test.end();
153 | }
154 | });
155 |
156 | tape("a serial queue of asynchronous closures processes tasks serially", function(test) {
157 | var tasks = [],
158 | task = asynchronousTask(),
159 | n = 10,
160 | q = queue.queue(1);
161 |
162 | while (--n >= 0) tasks.push(task);
163 | tasks.forEach(function(t) { q.defer(t); });
164 | q.awaitAll(callback);
165 |
166 | function callback(error, results) {
167 | test.equal(error, null);
168 | test.deepEqual(results, [
169 | {active: 1, index: 0},
170 | {active: 1, index: 1},
171 | {active: 1, index: 2},
172 | {active: 1, index: 3},
173 | {active: 1, index: 4},
174 | {active: 1, index: 5},
175 | {active: 1, index: 6},
176 | {active: 1, index: 7},
177 | {active: 1, index: 8},
178 | {active: 1, index: 9}
179 | ]);
180 | test.end();
181 | }
182 | });
183 |
184 | tape("a fully-concurrent queue of ten asynchronous tasks executes all tasks concurrently", function(test) {
185 | var t = asynchronousTask();
186 |
187 | queue.queue()
188 | .defer(t)
189 | .defer(t)
190 | .defer(t)
191 | .defer(t)
192 | .defer(t)
193 | .defer(t)
194 | .defer(t)
195 | .defer(t)
196 | .defer(t)
197 | .defer(t)
198 | .awaitAll(callback);
199 |
200 | function callback(error, results) {
201 | test.equal(null, error);
202 | test.deepEqual(results, [
203 | {active: 10, index: 0},
204 | {active: 9, index: 1},
205 | {active: 8, index: 2},
206 | {active: 7, index: 3},
207 | {active: 6, index: 4},
208 | {active: 5, index: 5},
209 | {active: 4, index: 6},
210 | {active: 3, index: 7},
211 | {active: 2, index: 8},
212 | {active: 1, index: 9}
213 | ]);
214 | test.end();
215 | }
216 | });
217 |
218 | tape("a partly-concurrent queue of ten asynchronous tasks executes at most three tasks concurrently", function(test) {
219 | var t = asynchronousTask();
220 |
221 | queue.queue(3)
222 | .defer(t)
223 | .defer(t)
224 | .defer(t)
225 | .defer(t)
226 | .defer(t)
227 | .defer(t)
228 | .defer(t)
229 | .defer(t)
230 | .defer(t)
231 | .defer(t)
232 | .awaitAll(callback);
233 |
234 | function callback(error, results) {
235 | test.equal(null, error);
236 | test.deepEqual(results, [
237 | {active: 3, index: 0},
238 | {active: 3, index: 1},
239 | {active: 3, index: 2},
240 | {active: 3, index: 3},
241 | {active: 3, index: 4},
242 | {active: 3, index: 5},
243 | {active: 3, index: 6},
244 | {active: 3, index: 7},
245 | {active: 2, index: 8},
246 | {active: 1, index: 9}
247 | ]);
248 | test.end();
249 | }
250 | });
251 |
252 | tape("a serialized queue of ten asynchronous tasks executes all tasks in series", function(test) {
253 | var t = asynchronousTask();
254 |
255 | queue.queue(1)
256 | .defer(t)
257 | .defer(t)
258 | .defer(t)
259 | .defer(t)
260 | .defer(t)
261 | .defer(t)
262 | .defer(t)
263 | .defer(t)
264 | .defer(t)
265 | .defer(t)
266 | .awaitAll(callback);
267 |
268 | function callback(error, results) {
269 | test.equal(null, error);
270 | test.deepEqual(results, [
271 | {active: 1, index: 0},
272 | {active: 1, index: 1},
273 | {active: 1, index: 2},
274 | {active: 1, index: 3},
275 | {active: 1, index: 4},
276 | {active: 1, index: 5},
277 | {active: 1, index: 6},
278 | {active: 1, index: 7},
279 | {active: 1, index: 8},
280 | {active: 1, index: 9}
281 | ]);
282 | test.end();
283 | }
284 | });
285 |
286 | tape("a serialized queue of ten deferred synchronous tasks executes all tasks in series, within the callback of the first task", function(test) {
287 | var t = deferredSynchronousTask();
288 |
289 | queue.queue(1)
290 | .defer(t)
291 | .defer(t)
292 | .defer(t)
293 | .defer(t)
294 | .defer(t)
295 | .defer(t)
296 | .defer(t)
297 | .defer(t)
298 | .defer(t)
299 | .defer(t)
300 | .awaitAll(callback);
301 |
302 | t.finish();
303 |
304 | function callback(error, results) {
305 | test.equal(null, error);
306 | test.deepEqual(results, [
307 | {active: 1, index: 0},
308 | {active: 2, index: 1},
309 | {active: 2, index: 2},
310 | {active: 2, index: 3},
311 | {active: 2, index: 4},
312 | {active: 2, index: 5},
313 | {active: 2, index: 6},
314 | {active: 2, index: 7},
315 | {active: 2, index: 8},
316 | {active: 2, index: 9}
317 | ]);
318 | test.end();
319 | }
320 | });
321 |
322 | tape("a partly-concurrent queue of ten synchronous tasks executes all tasks in series", function(test) {
323 | var t = synchronousTask();
324 |
325 | queue.queue(3)
326 | .defer(t)
327 | .defer(t)
328 | .defer(t)
329 | .defer(t)
330 | .defer(t)
331 | .defer(t)
332 | .defer(t)
333 | .defer(t)
334 | .defer(t)
335 | .defer(t)
336 | .awaitAll(callback);
337 |
338 | function callback(error, results) {
339 | test.equal(null, error);
340 | test.deepEqual(results, [
341 | {active: 1, index: 0},
342 | {active: 1, index: 1},
343 | {active: 1, index: 2},
344 | {active: 1, index: 3},
345 | {active: 1, index: 4},
346 | {active: 1, index: 5},
347 | {active: 1, index: 6},
348 | {active: 1, index: 7},
349 | {active: 1, index: 8},
350 | {active: 1, index: 9}
351 | ]);
352 | test.end();
353 | }
354 | });
355 |
356 | tape("a serialized queue of ten synchronous tasks executes all tasks in series", function(test) {
357 | var t = synchronousTask();
358 |
359 | queue.queue(1)
360 | .defer(t)
361 | .defer(t)
362 | .defer(t)
363 | .defer(t)
364 | .defer(t)
365 | .defer(t)
366 | .defer(t)
367 | .defer(t)
368 | .defer(t)
369 | .defer(t)
370 | .awaitAll(callback);
371 |
372 | function callback(error, results) {
373 | test.equal(null, error);
374 | test.deepEqual(results, [
375 | {active: 1, index: 0},
376 | {active: 1, index: 1},
377 | {active: 1, index: 2},
378 | {active: 1, index: 3},
379 | {active: 1, index: 4},
380 | {active: 1, index: 5},
381 | {active: 1, index: 6},
382 | {active: 1, index: 7},
383 | {active: 1, index: 8},
384 | {active: 1, index: 9}
385 | ]);
386 | test.end();
387 | }
388 | });
389 |
390 | tape("a huge queue of deferred synchronous tasks does not throw a RangeError", function(test) {
391 | var t = deferredSynchronousTask(),
392 | q = queue.queue(),
393 | n = 200000;
394 |
395 | for (var i = 0; i < n; ++i) q.defer(t);
396 | t.finish();
397 | q.awaitAll(callback);
398 |
399 | function callback(error, results) {
400 | test.equal(null, error);
401 | test.equal(results.length, n);
402 | test.end();
403 | }
404 | });
405 |
406 | tape("if a task calls back successfully more than once, subsequent calls are ignored", function(test) {
407 | queue.queue()
408 | .defer(function(callback) { setTimeout(function() { callback(null, 1); }, 100); })
409 | .defer(function(callback) { callback(null, 2); process.nextTick(function() { callback(null, -1); }); })
410 | .defer(function(callback) { callback(null, 3); process.nextTick(function() { callback(new Error("foo")); }); })
411 | .defer(function(callback) { process.nextTick(function() { callback(null, 4); }); setTimeout(function() { callback(new Error("bar")); }, 100); })
412 | .await(callback);
413 |
414 | function callback(error, one, two, three, four) {
415 | test.equal(error, null);
416 | test.equal(one, 1);
417 | test.equal(two, 2);
418 | test.equal(three, 3);
419 | test.equal(four, 4);
420 | test.end();
421 | }
422 | });
423 |
424 | tape("if a task calls back with an error more than once, subsequent calls are ignored", function(test) {
425 | queue.queue()
426 | .defer(function(callback) { setTimeout(function() { callback(null, 1); }, 100); })
427 | .defer(function(callback) { callback(new Error("foo")); process.nextTick(function() { callback(new Error("bar")); }); })
428 | .defer(function(callback) { process.nextTick(function() { callback(new Error("bar")); }); setTimeout(function() { callback(new Error("baz")); }, 100); })
429 | .await(callback);
430 |
431 | function callback(error) {
432 | test.equal(error.message, "foo");
433 | test.end();
434 | }
435 | });
436 |
437 | tape("if a task throws an error aftering calling back synchronously, the error is ignored", function(test) {
438 | queue.queue()
439 | .defer(function(callback) { callback(null, 1); throw new Error; })
440 | .await(callback);
441 |
442 | function callback(error, one) {
443 | test.equal(error, null);
444 | test.equal(one, 1);
445 | test.end();
446 | }
447 | });
448 |
449 | tape("if the await callback throws an error aftering calling back synchronously, the error is thrown", function(test) {
450 | queue.queue(1)
451 | .defer(function(callback) { process.nextTick(callback); })
452 | .defer(function(callback) { callback(null, 1); })
453 | .await(function() { throw new Error("foo"); });
454 |
455 | process.once("uncaughtException", function(error) {
456 | test.equal(error.message, "foo");
457 | test.end();
458 | });
459 | });
460 |
461 | tape("if a task errors, another task can still complete successfully, and is ignored", function(test) {
462 | queue.queue()
463 | .defer(function(callback) { setTimeout(function() { callback(null, 1); }, 10); })
464 | .defer(function(callback) { callback(new Error("foo")); })
465 | .await(callback);
466 |
467 | function callback(error) {
468 | test.equal(error.message, "foo");
469 | test.end();
470 | }
471 | });
472 |
473 | tape("if a task errors, it is not subsequently aborted", function(test) {
474 | var aborted = false;
475 |
476 | var q = queue.queue()
477 | .defer(function(callback) { process.nextTick(function() { callback(new Error("foo")); }); return {abort: function() { aborted = true; }}; })
478 | .await(callback);
479 |
480 | function callback(error) {
481 | test.equal(error.message, "foo");
482 | test.equal(aborted, false);
483 | test.end();
484 | }
485 | });
486 |
487 | tape("a task that defers another task is allowed", function(test) {
488 | var q = queue.queue();
489 |
490 | q.defer(function(callback) {
491 | callback(null);
492 | q.defer(function(callback) {
493 | test.end();
494 | });
495 | });
496 | });
497 |
498 | tape("a falsey error is still considered an error", function(test) {
499 | queue.queue()
500 | .defer(function(callback) { callback(0); })
501 | .defer(function() { throw new Error; })
502 | .await(function(error) { test.equal(error, 0); test.end(); });
503 | });
504 |
505 | tape("if the await callback is set during abort, it only gets called once", function(test) {
506 | var q = queue.queue();
507 | q.defer(function() { return {abort: function() { q.await(callback); }}; });
508 | q.defer(function() { throw new Error("foo"); });
509 |
510 | function callback(error) {
511 | test.equal(error.message, "foo");
512 | test.end();
513 | }
514 | });
515 |
516 | tape("aborts a queue of partially-completed asynchronous tasks", function(test) {
517 | var shortTask = abortableTask(50),
518 | longTask = abortableTask(5000);
519 |
520 | var q = queue.queue()
521 | .defer(shortTask)
522 | .defer(longTask)
523 | .defer(shortTask)
524 | .defer(longTask)
525 | .defer(shortTask)
526 | .defer(longTask)
527 | .defer(shortTask)
528 | .defer(longTask)
529 | .defer(shortTask)
530 | .defer(longTask)
531 | .awaitAll(callback);
532 |
533 | setTimeout(function() {
534 | q.abort();
535 | }, 250);
536 |
537 | function callback(error, results) {
538 | test.equal(error.message, "abort");
539 | test.equal(results, undefined);
540 | test.equal(shortTask.aborted(), 0);
541 | test.equal(longTask.aborted(), 5);
542 | test.end();
543 | }
544 | });
545 |
546 | tape("aborts an entire queue of asynchronous tasks", function(test) {
547 | var longTask = abortableTask(5000);
548 |
549 | var q = queue.queue()
550 | .defer(longTask)
551 | .defer(longTask)
552 | .defer(longTask)
553 | .defer(longTask)
554 | .defer(longTask)
555 | .awaitAll(callback);
556 |
557 | setTimeout(function() {
558 | q.abort();
559 | }, 250);
560 |
561 | function callback(error, results) {
562 | test.equal(error.message, "abort");
563 | test.equal(results, undefined);
564 | test.equal(longTask.aborted(), 5);
565 | test.end();
566 | }
567 | });
568 |
569 | tape("does not abort tasks that have not yet started", function(test) {
570 | var shortTask = abortableTask(50),
571 | longTask = abortableTask(5000);
572 |
573 | var q = queue.queue(2) // enough for two short tasks to run
574 | .defer(shortTask)
575 | .defer(longTask)
576 | .defer(shortTask)
577 | .defer(longTask)
578 | .defer(shortTask)
579 | .defer(longTask)
580 | .defer(shortTask)
581 | .defer(longTask)
582 | .defer(shortTask)
583 | .defer(longTask)
584 | .awaitAll(callback);
585 |
586 | setTimeout(function() {
587 | q.abort();
588 | }, 250);
589 |
590 | function callback(error, results) {
591 | test.equal(error.message, "abort");
592 | test.equal(results, undefined);
593 | test.equal(shortTask.aborted(), 0);
594 | test.equal(longTask.aborted(), 2);
595 | test.end();
596 | }
597 | });
598 |
--------------------------------------------------------------------------------
/test/synchronousTask.js:
--------------------------------------------------------------------------------
1 | module.exports = function(counter) {
2 | var active = 0;
3 |
4 | if (!counter) counter = {scheduled: 0};
5 |
6 | return function(callback) {
7 | try {
8 | callback(null, {active: ++active, index: counter.scheduled++});
9 | } finally {
10 | --active;
11 | }
12 | };
13 | };
14 |
--------------------------------------------------------------------------------