I am using the node async lib - https://github.com/caolan/async#forEach and would like to iterate through an array (arrayOne), push the result to another(productList), and pass that array to the final function. However the printed result is an empty array.
function Async(callback) {
var productList = [];
async.forEach(
arrayOne,
function(item, callback){
getClientsNb({id:item["row"][0]},function (result) {
productList.push(result)
});
callback();
},
function(err) {
console.log(productList);
}
);
}
the "getCLientsNb" function is a call to a Neo4j database.
I would like to understand why the result is an empty array. Since I am a beginner in node.js, please be very clear in your answer :)
Your problem is where you place your callback.
function(item, callback)
{ getClientsNb({id:item["row"][0]},function
(result) { productList.push(result) });
callback(); }
The outer function returns before the callback for getClientsNb() is executed, so you never build up your list. You need to move the callback inside that function:
function(item, callback){ getClientsNb({id:item["row"][0]},
function (result) {
productList.push(result)
callback()});
}
If you used async.map instead of forEach, then you wouldn't need to create a productList. Just pass the result in the second parameter to the callback and it would be passed to the final function as the second parameter.