I am on the recieving end of a POST call which contains an array of objects (requestArray). Before I respond to the POST, I need to pass the array's objects through a series of functions, in sequence. I chose the async library to help me with this task however I'm having difficulty controlling the code's execution flow.
I am using a global array to store the results of each function (responseArray). Some of the functions depend on the result of prior functions. I don't want to use async.waterfall() because 1. I'll have to rewrite my code and 2. I may encounter the same early loop termination issue. Below is my code problematic code.
app.post('/test', function(req, res) {
var importArray = req.body;
var iteration = 0;
async.eachSeries(importArray, function(data, callback) {
var index = importArray.indexOf(data);
var element = data.element;
exportArray[index] = [];
async.series([
function(callback) {
process1(data, index, callback);
},
function(callback) {
process2(element, index, callback);
},
function(callback) {
process3(element, index, callback);
}],
function(err, results) {
var str = {};
results.forEach(function(result) {
if (result) {
str += result + ',';
}
});
//callback(); // callback here = synchronous execution.
if (index === req.body.length - 1) {
res.send(exportArray);
}
});
console.log('async.eachSeries() callback iteration # = ' + iteration);
iteration++;
callback(); // callback here = asynchronous execution.
}, function(err){
if( err ) {
console.log('Error');
} else {
console.log('All data has been processes successfully.');
}
});
});
Each function in the async.series() returns callback(null, result). After process1() returns its callback, the async.eachSeries() jumps to the next array entry before, which is ideal. However, async.eachSeries() executes a POST response before all of the async.series() results are returned. How could I revise my code so that async.eachSeries() finishes execution after all of the importArray results (exportArray) are returned from process1 - 3 before I send a POST response?