-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Description
Hello!
I love to use async.auto for easy controlling control flow even in situation, which does not strictly require parallel execution. But it has nice feature - easily manageable dependencies of each tasks.
But there is one thing, that bugs me. If i ever want to use results from previous tasks, the task function have to know exact string name of that previous task. Which is not good, because that function might be from another file. When someone change that string name, not-so-easily-spottable bug appears.
Example (As you seee, inside function "bbb", i must know name "a"):
async.auto({
a: aaa,
b: ["a", bbb],
c: ["a", ccc]
});
function bbb(callback, results){
var someResult = results.a;
}
My proposal for this use case is to have some wrapper, which turns dependency list into arguments, so you only need to know names in defining async.auto.
Example of desired use and its equivalent:
async.auto({
a: async.wrapArgs(aaa),
b: async.wrapArgs(bbb, "a"),
c: async.wrapArgs(ccc, "b", "a")
}, function(error, results){
console.log("done", results);
});
async.auto({
a: aaa,
b: ["a", function(callback, results){
bbb(callback, results.a)
}],
c: ["b" ,"a", function(callback, results){
ccc(callback, results.b, results.a)
}]
});
function bbb(callback, a){};
function ccc(callback, b, a){};
In the end, i wrote some simple wrapper to demonstrate funcionality, which i am now offering for async, in case you decide its good pattern and practice for others :) (i will use it anyway).
async.wrapArgs = function(){
var args = Array.prototype.slice.call(arguments, 0);
var oldFn = arguments[0];
var requires = args.slice(1, args.length) || [];
var newFn = function(callback, results){
var newArgs = requires.map(function(key){
return results[key];
});
newArgs.unshift(callback);
oldFn.apply(null, newArgs);
}
return requires.concat([newFn]);
}