Question

I don't know if there is a term for the thing i ask about, so i'll try to illustrate it:

I Got a function that takes an array of contacts, and loop them through to update their status on the website. The 'something.getStatus' function does not return anything, but upon successful completion, it gives the status (online/offline/etc.) of the user.

The problem here is, when the function inside is called, the variable user_id is the last one in the array for all the function calls, making it impossible to know how have what status.

function gotGroupContacts(contacts) {

 for ( i = 0; i < contacts.length; i++) {
  var user_id = contacts[i];
  something.getStatus(user_id, function(resp) {
   updateLinkStatus(user_id, resp.status, resp.statusMessage);
  }, getStatusErrorHandler);
 }
}

Is there any way i can 'lock' the variable, or otherwise pass it to the function within?

Was it helpful?

Solution

enclose your getStatus method call in a closure, like so

for ( i = 0; i < contacts.length; i++) {
  var user_id = contacts[i];
  (function(uid) {
     something.getStatus(uid, function(resp) {
        updateLinkStatus(uid, resp.status, resp.statusMessage);
     }, getStatusErrorHandler);
  }(user_id))
}

user_id is passed into the anonymous self-executed function, and this ensure to have the right value

OTHER TIPS

if your script doesn't need to be compatible with IE <9, you can write like this:

function gotGroupContacts(contacts) {
  contacts.forEach(function(user_id){
     something.getStatus(user_id, function(resp) {
        updateLinkStatus(user_id, resp.status, resp.statusMessage);
     }, getStatusErrorHandler);
  });
}

NOTICE: forEach method can be easily ported to IE, see this: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top