0

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 :)

1
  • is it even iterates inside getClientsNb callback? have you tried to put console.log(result) near productList.push(result) ? Commented Mar 12, 2016 at 15:03

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.