For loop in node.js is behaving quite weirdly. code is as below:
for(var i = 0; i < req.body.stages.length; i++){
if (req.body.current_stage == req.body.stages[i].stage_short_desc){
console.log('value of i :'+ i)
Application.findOne({ application_num: req.params.id }, (error, application) => {
if (error) {
logger.error('Application not found' + error)
} else {
console.log('reached here : ' + i)
console.log(req.body.stages[i].requisites.length)
....
}
})
}
}
And result is:
value of i :0 reached here : 8 error: uncaughtException: Cannot read property 'requisites' of undefined.
req.body.current_stage == req.body.stages[i].stage_short_desc ---> happens at i = 0
I am surprised, when index i was 0, it is entering into if loop and satisfies the condition, hence first line of result. Then find the application from database, if successful then if we notice value of index i is 8 (which is maximum value of index). Can anyone please suggest how this is possible?
Thanks!