how to handle closure in node.js

server.getchannel are closures over the i variable (well, over everything in scope, but it’s i we’re concerned with). They get an enduring reference to i, not a copy of its value as of when the function was created. That means when the function runs, it uses the current value of i, not the value as it was when the function was created. The upshot is that all of those functions will use the same value of i, which is the value as of the end of the loop. Since that’s beyond the end of the array, resultscard[i] is undefined and so trying to read an ownerproperty from it fails. (More about closures: Closures are not complicated)

for (var i=0; i<resultscard.length;i++) {    
   console.log('card owner'+resultscard[i].owner);      
 //checking that any users is in inside of gib      
server.getchannel("channels."+request.gibid+'-I', makeCallback(i));         
// Call the factory function, passing in `i` -----^      
   if(i==resultscard.length-1) {           
if (response.users.length<=0) {             
//here need to send sorry event that no owner is online             
 } else {        
}           return proceed(true,response);        
 }       });     
}     // The factory function        
 function makeCallback(index) {     
  return function(err, channel) {         
if (channel.users) {          
 var arr=channel.users.split(',');          
 // Note we use `index` -- our argument -- not `i` below        
   if (functions.in_array(resultscard[index].owner, arr)) {          
   response.users.push(resultscard[index].owner);           }         }       };     }

Now the callback we create in makeCallback closes over the index argument for the call that created it, which nothing other changes. We pass i in, and there we are. It’s still a closure over the other things (because of where makeCallback is defined), but it uses index with them so it handles the right entry.

for(var i=0; i < count; i++){
   (function(index) {

Ref :


About rahul23134654

Hi, I am Rahul Meha , B.E. in (I.T.)
This entry was posted in Node.js. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s