0

I'm fairly new to node.js and sails.js but not to javascript I have a simple function that iterates over an array of abjects, validates them, each validated object in the array is pushed into another array with i want to pass onto my my view.

if(results){
    var items = results.one;
    var toReturn = [];
    for(var i = 0; i<items.length; i++){
        var item = items[i];
        Inventory.findOne({primaryKey: item.primaryKey}, function(err, found){
            if(err){
                res.send("Err reached");
            }
            else{
                //Some validation code

                if (validations_failed_condition){
                    console.log("FAiled validations");
                }
                else{
                    console.log("Validations passed, Pushing item");
                    console.log(item);
                    toReturn.push(item);
                }
            }
        });
    }
    res.send(toReturn);
}

Even though my logs are showing me multiple items are being validated and being pushed into my array toReturn. The data being sent to the view is an empty array.

Is for looping in node.js asynchronous ? Is data being passed to the view before the for loop is completed ?

What can I do to fix this ?

Thilina Sampath
  • 3,615
  • 6
  • 39
  • 65
user434885
  • 1,988
  • 6
  • 29
  • 51
  • Not the loop is asynchronous, but the `findOne` method that you start in the loop body. – Bergi Jun 02 '14 at 19:24
  • @Bergi i figured that would be the problem. how can i fix this ? – user434885 Jun 02 '14 at 19:42
  • 1
    You need to put `res.send` in a callback that runs after the last `findOne` callback. [Promises](https://github.com/petkaantonov/bluebird/blob/master/API.md#mapfunction-mapper---promise) or [asnyc.js](https://github.com/caolan/async#map) libraries can help with that. – Bergi Jun 02 '14 at 19:47
  • possible duplicate of [The best pattern for handling async looping in Node.js](http://stackoverflow.com/questions/8579557/the-best-pattern-for-handling-async-looping-in-node-js) – sgress454 Jun 02 '14 at 21:01

0 Answers0