Skip to content

Commit 27230c2

Browse files
committed
added autoInject, adapted from #608
1 parent f6a19ce commit 27230c2

File tree

4 files changed

+198
-1
lines changed

4 files changed

+198
-1
lines changed

README.md

+73-1
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,7 @@ Some functions are also available in the following forms:
219219
* [`queue`](#queue), [`priorityQueue`](#priorityQueue)
220220
* [`cargo`](#cargo)
221221
* [`auto`](#auto)
222+
* [`autoInject`](#autoInject)
222223
* [`retry`](#retry)
223224
* [`iterator`](#iterator)
224225
* [`times`](#times), `timesSeries`, `timesLimit`
@@ -1291,7 +1292,7 @@ methods:
12911292
* `saturated` - A callback that is called when the `queue.length()` hits the concurrency and further tasks will be queued.
12921293
* `empty` - A callback that is called when the last item from the `queue` is given to a `worker`.
12931294
* `drain` - A callback that is called when the last item from the `queue` has returned from the `worker`.
1294-
* `idle()`, `pause()`, `resume()`, `kill()` - cargo inherits all of the same methods and event calbacks as [`queue`](#queue)
1295+
* `idle()`, `pause()`, `resume()`, `kill()` - cargo inherits all of the same methods and event callbacks as [`queue`](#queue)
12951296
12961297
__Example__
12971298
@@ -1420,6 +1421,77 @@ function(err, results){
14201421
14211422
For a complicated series of `async` tasks, using the [`auto`](#auto) function makes adding new tasks much easier (and the code more readable).
14221423
1424+
---------------------------------------
1425+
<a name="autoInject" />
1426+
### autoInject(tasks, [callback])
1427+
1428+
A dependency-injected version of the [`auto`](#auto) function. Dependent tasks are specified as parameters to the function, after the usual callback parameter, with the parameter names matching the names of the tasks it depends on. This can provide even more readable task graphs which can be easier to maintain.
1429+
1430+
If a final callback is specified, the task results are similarly injected, specified as named parameters after the initial error parameter.
1431+
1432+
The autoInject function is purely syntactic sugar and its semantics are otherwise equivalent to [`auto`](#auto).
1433+
1434+
__Arguments__
1435+
1436+
* `tasks` - An object, each of whose properties is a function of the form
1437+
'func([dependencies...], callback). The object's key of a property serves as the name of the task defined by that property, i.e. can be used when specifying requirements for other tasks.
1438+
* The `callback` parameter is a `callback(err, result)` which must be called when finished, passing an `error` (which can be `null`) and the result of the function's execution. The remaining parameters name other tasks on which the task is dependent, and the results from those tasks are the arguments of those parameters.
1439+
* `callback(err, [results...])` - An optional callback which is called when all the tasks have been completed. It receives the `err` argument if any `tasks` pass an error to their callback. The remaining parameters are task names whose results you are interested in. This callback will only be called when all tasks have finished or an error has occurred, and so do not not specify dependencies in the same way as `tasks` do. If an error occurs, no further `tasks` will be performed, and `results` will only be valid for those tasks which managed to complete.
1440+
1441+
1442+
__Example__
1443+
1444+
The example from [`auto`](#auto) can be rewritten as follows:
1445+
1446+
```js
1447+
async.autoInject({
1448+
get_data: function(callback){
1449+
// async code to get some data
1450+
callback(null, 'data', 'converted to array');
1451+
},
1452+
make_folder: function(callback){
1453+
// async code to create a directory to store a file in
1454+
// this is run at the same time as getting the data
1455+
callback(null, 'folder');
1456+
},
1457+
write_file: function(get_data, make_folder, callback){
1458+
// once there is some data and the directory exists,
1459+
// write the data to a file in the directory
1460+
callback(null, 'filename');
1461+
},
1462+
email_link: function(write_file, callback){
1463+
// once the file is written let's email a link to it...
1464+
// write_file contains the filename returned by write_file.
1465+
callback(null, {'file':write_file, 'email':'[email protected]'});
1466+
}
1467+
}, function(err, email_link) {
1468+
console.log('err = ', err);
1469+
console.log('email_link = ', email_link);
1470+
});
1471+
```
1472+
1473+
If you are using a minifier that mangles parameter names, `autoInject` will not work with plain functions. To work around this, you can explicitly specify the names of the parameters in an array, similar to Angular.js dependency injection.
1474+
1475+
```js
1476+
async.autoInject({
1477+
//...
1478+
write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback){
1479+
// once there is some data and the directory exists,
1480+
// write the data to a file in the directory
1481+
callback(null, 'filename');
1482+
}],
1483+
email_link: ['write_file', function(write_file, callback){
1484+
// once the file is written let's email a link to it...
1485+
// write_file contains the filename returned by write_file.
1486+
callback(null, {'file':write_file, 'email':'[email protected]'});
1487+
}]
1488+
//...
1489+
},
1490+
```
1491+
1492+
This still has an advantage over plain `auto`, since the results a task depends on are still spread into arguments.
1493+
1494+
14231495
---------------------------------------
14241496
14251497
<a name="retry"></a>

lib/autoInject.js

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import auto from './auto';
2+
import forOwn from 'lodash/forOwn';
3+
import arrayMap from 'lodash/_arrayMap';
4+
import isArray from 'lodash/isArray';
5+
6+
var argsRegex = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
7+
8+
function parseParams(func) {
9+
return func.toString().match(argsRegex)[1].split(/\s*\,\s*/);
10+
}
11+
12+
export default function autoInject(tasks, callback) {
13+
var newTasks = {};
14+
15+
forOwn(tasks, function (taskFn, key) {
16+
var params;
17+
18+
if (isArray(taskFn)) {
19+
params = [...taskFn];
20+
taskFn = params.pop();
21+
22+
newTasks[key] = [...params].concat(newTask);
23+
} else if (taskFn.length === 0) {
24+
throw new Error("autoInject task functions require explicit parameters.");
25+
} else if (taskFn.length === 1) {
26+
// no dependencies
27+
newTasks[key] = taskFn;
28+
} else {
29+
params = parseParams(taskFn);
30+
params.pop();
31+
32+
newTasks[key] = [...params].concat(newTask);
33+
34+
}
35+
36+
function newTask(results, taskCb) {
37+
var newArgs = arrayMap(params, function (name) {
38+
return results[name];
39+
});
40+
taskFn(...newArgs.concat(taskCb));
41+
}
42+
});
43+
44+
auto(newTasks, callback);
45+
}

lib/index.js

+3
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import applyEachSeries from './applyEachSeries';
55
import apply from './apply';
66
import asyncify from './asyncify';
77
import auto from './auto';
8+
import autoInject from './autoInject';
89
import cargo from './cargo';
910
import compose from './compose';
1011
import concat from './concat';
@@ -71,6 +72,7 @@ export default {
7172
apply: apply,
7273
asyncify: asyncify,
7374
auto: auto,
75+
autoInject: autoInject,
7476
cargo: cargo,
7577
compose: compose,
7678
concat: concat,
@@ -155,6 +157,7 @@ export {
155157
apply as apply,
156158
asyncify as asyncify,
157159
auto as auto,
160+
autoInject as autoInject,
158161
cargo as cargo,
159162
compose as compose,
160163
concat as concat,

mocha_test/autoInject.js

+77
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
var async = require('../lib');
2+
var expect = require('chai').expect;
3+
var _ = require('lodash');
4+
5+
describe('autoInject', function () {
6+
7+
it("basics", function (done) {
8+
var callOrder = [];
9+
async.autoInject({
10+
task1: function(task2, callback){
11+
expect(task2).to.equal(2);
12+
setTimeout(function(){
13+
callOrder.push('task1');
14+
callback(null, 1);
15+
}, 25);
16+
},
17+
task2: function(callback){
18+
setTimeout(function(){
19+
callOrder.push('task2');
20+
callback(null, 2);
21+
}, 50);
22+
},
23+
task3: function(task2, callback){
24+
expect(task2).to.equal(2);
25+
callOrder.push('task3');
26+
callback(null, 3);
27+
},
28+
task4: function(task1, task2, callback){
29+
expect(task1).to.equal(1);
30+
expect(task2).to.equal(2);
31+
callOrder.push('task4');
32+
callback(null, 4);
33+
},
34+
task5: function(task2, callback){
35+
expect(task2).to.equal(2);
36+
setTimeout(function(){
37+
callOrder.push('task5');
38+
callback(null, 5);
39+
}, 0);
40+
},
41+
task6: function(task2, callback){
42+
expect(task2).to.equal(2);
43+
callOrder.push('task6');
44+
callback(null, 6);
45+
}
46+
},
47+
function(err, results){
48+
expect(results.task6).to.equal(6);
49+
expect(callOrder).to.eql(['task2','task6','task3','task5','task1','task4']);
50+
done();
51+
});
52+
});
53+
54+
it('should work with array tasks', function (done) {
55+
var callOrder = [];
56+
57+
async.autoInject({
58+
task1: function (cb) {
59+
callOrder.push('task1');
60+
cb(null, 1);
61+
},
62+
task2: ['task3', function (task3, cb) {
63+
expect(task3).to.equal(3);
64+
callOrder.push('task2');
65+
cb(null, 2);
66+
}],
67+
task3: function (cb) {
68+
callOrder.push('task3');
69+
cb(null, 3);
70+
}
71+
}, function () {
72+
expect(callOrder).to.eql(['task1','task3','task2']);
73+
done();
74+
});
75+
});
76+
77+
});

0 commit comments

Comments
 (0)