I am trying to learn how to use the async module in node.js and I fall into to the following problem:
I first wrote this script which works fine (to my understanding)
var async = require('async');
var seconds_values = [];
process();
function process() {
var names = ['One', 'Two', 'ten', 'hello'];
modifications(names);
}
function modifications(somenames) {
async.each(somenames, function (one_name, callback) {
var random_num = Math.floor((Math.random() * 100000000) + 1);
seconds_values.push(one_name + '_' + random_num);
callback();
}, function(err){
async.each(seconds_values, function (one_value, callback) {
console.log(one_value);
callback();
},
function(err){
console.log('==== The END ===');
});
});
}
The I tried to assign the iterator to a variable, to make the code more readable.
var async = require('async');
var seconds_values = [];
process();
function process() {
var names = ['One', 'Two', 'ten', 'hello'];
modifications(names);
}
var first_function = function (one_name, callback) {
var random_num = Math.floor((Math.random() * 100000000) + 1);
seconds_values.push(one_name + '_' + random_num);
callback();
}
function modifications(somenames) {
async.each(somenames, first_function, function(err){
async.each(seconds_values, function (one_value, callback) {
console.log(one_value);
callback();
},
function(err){
console.log('==== The END ===');
});
});
}
The second script gives me the following error:
iterator(x, only_once(done) );
^
TypeError: undefined is not a function
I think I am missing something fundamental here. Could you please point me out what, if possible?
The error occurs because when the process
runs, it calls modifications
, but at this time, first_function
is not defined yet.
You can have two options:
1.put the declaration before process call:
var first_function = function (one_name, callback) {
var random_num = Math.floor((Math.random() * 100000000) + 1);
seconds_values.push(one_name + '_' + random_num);
callback();
}
process();
2. use function declaration:
function first_function(one_name, callback) {
var random_num = Math.floor((Math.random() * 100000000) + 1);
seconds_values.push(one_name + '_' + random_num);
callback();
}
Also see here: Link