-2

Following is my code -

exports.saveWeekAvailability = function(req, res){
    console.log("-- SAVE WEEK WISE DATA --");

    weekData = req.body;
    var resultArr = [];
    for(var i=0; i< weekData.length; i++){
        Availability(weekData[i]).save(function(err, result){
            console.log("------------------------------------------");
            console.log(result);
            resultArr.push(result);
        });
    }
    console.log("-- Result Arr --");
    console.log(resultArr);

};

But every time resultArr is an empty array. Let me know what I am doing wrong here.

Trialcoder
  • 5,816
  • 9
  • 44
  • 66

1 Answers1

1

This is a duplicate. Check comments to your answer for duplicated post which contains a very good answer if you want to understand what is going on.

A quick solution for your problem:

for(var i=0; i< weekData.length; i++){
   (function(j) {
        Availability(weekData[i]).save(function(err, result){
            console.log("------------------------------------------");
            console.log(result);
            resultArr.push(result);
            if ( j == weekData.length - 1 ) {
                console.log("-- Result Arr --");
                console.log(resultArr);
            }
        });
    }(i));
}
fmsf
  • 36,317
  • 49
  • 147
  • 195
  • Thx..but to be very honest I tried ang googled before..but dont know this is a case of `closure`..so how do users expect from a novice to search with the right term and then downvote the question :( – Trialcoder Sep 22 '14 at 10:50
  • This is what I tried too but no luck so I asked here http://pastebin.com/Zu0D7bVg – Trialcoder Sep 22 '14 at 10:52
  • @Trialcoder, I read your code in pastebin, you can't return a value from inside a callback. – fmsf Sep 22 '14 at 10:53