Jason Mishou Jason Mishou - 1 month ago 14
Node.js Question

nested async.eachOfSeries TypeError: innerCallback is not a function

I am fairly new to javascript and have a bunch of synchronous code that I am trying to turn asynchrnous. I have a library that has lots of data intensive for loops. So far I have been able to easily convert the non-nested loops using the async library but I have run into a problem with nested loops.

When running the code below I get

TypeError: innerCallback is not a function


Any help would be greatly appreciated. Hopefully I am overlooking something small.

var async = require("async");

var byteArray = [
[1, 1, 1, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 0]
];

async.eachOfSeries(byteArray, function(bytes, x_index, outerCallback) {
console.log(bytes);

async.eachSeries(bytes, function(bits, y_index, innerCallback) {
console.log(bits);
innerCallback();
});

outerCallback();

}, function(err) {
if (err) console.error(err.message);
});

Answer

You can either use eachOfSeries in both the inner and outer iterations

var byteArray = [
    [1, 1, 1, 1, 1, 1, 1, 0],
    [0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 1, 1, 0, 0, 0],
    [0, 0, 0, 0, 0, 1, 0, 0],
    [1, 1, 1, 1, 1, 1, 1, 0]
];

async.eachOfSeries(byteArray, function(bytes, x_index, outerCallback) {
    async.eachOfSeries(bytes, function(bits, y_index, innerCallback) {
        console.log(bits);
        innerCallback();
    });
	console.log('\n\n')
    outerCallback();

}, function(err) {
    if (err) console.error(err.message);
    console.log('done')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/async/2.1.2/async.js"></script>

Or you can keep on using eachSeries but it seems the documentation is somewhat mistaken when it states that the arguments are

eachSeries(coll, iteratee, callback)

It seems it's actually

eachSeries(coll, callback)

making your code look like

var byteArray = [
    [1, 1, 1, 1, 1, 1, 1, 0],
    [0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 1, 1, 0, 0, 0],
    [0, 0, 0, 0, 0, 1, 0, 0],
    [1, 1, 1, 1, 1, 1, 1, 0]
];

async.eachOfSeries(byteArray, function(bytes, x_index, outerCallback) {
	
    async.eachSeries(bytes, function(bits, innerCallback) {
        console.log(bits);
        innerCallback();
    });
	console.log('\n\n')
    outerCallback();

}, function(err) {
    if (err) console.error(err.message);
    console.log('done')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/async/2.1.2/async.js"></script>