I have written a piece of code that for each entry of an array of users given, should call a function that modifies such user and sends email about their membership expiration.
The strange behaviour (I am quite sure I got how the scope works) are two:
If I don't assign
users[i]
tofoo
, the lineldapclient.modify(users[i].dn, change, function(err) {
does know whatusers[i]
is, but the function does not ("error, cannot read property 'cn' of undefined")if I do assign foo, the function runs correctly - however, the result of sendMail is all the times the same (if I have 4 different users, there will be 4 sent emails which are the same and sent to one user)
Here's the code snippet
for ( var i = 0; i < users.length; ++i ){
var foo = users[i];
ldapclient.modify(foo.dn, change, function(err) {
log.info({change: change, err: err}, 'Modifying Membership');
assert.ifError(err);
//send mail accordingly
var mailmessage = {
to: foo.cn+" <"+foo.mail+">",
subject: "Your membership has expired",
text: "Hi "+foo.cn+", \n your membership for the body " + foo.body + " \
has been suspended after automatic expiration"
};
mail.sendMail(mailmessage);
}
I was quite sure of having understood the scope and the magic of anonymous functions, async stuff, callbacks, and anything that makes node "cool", but this (mainly my point 2) just destroys all my beliefs.