Is there a way to pass information to an async.js parallel call so I don't have to use global variables?
async.parallel([
function(callback){
setTimeout(function(){
callback(null, 'one');
}, 200);
},
function(callback){
setTimeout(function(){
callback(null, 'two');
}, 100);
},
],
// optional callback
function(err, results){
console.log(info)
// the results array will equal ['one','two'] even though
// the second function had a shorter timeout.
});
I would like for the final callback to be aware of the value of "info". Thanks for your help!
To avoid introducing a global variable you could place it within an enclosure:-
(function() {
var info = "Some info";
async.parallel([
function(callback) {
setTimeout(function() {
callback(null, "one");
}, 200);
},
function(callback) {
setTimeout(function() {
callback(null, "two");
}, 100);
}
],
function(error, result) {
console.log(info);
});
}) ();
That way the final callback has access to it but it won't be visible outside of the scope of the anonymous self-executing function that encloses that code.
EDIT To do an enclosure in coffeescript:-
(() ->
# my code
)()
Another way would be:
(function(protectedVariable1,protectedVariable2) {
//do something with protected variables
})(variable1,variable2);