0

I am working on chrome extension (StackEye) and as per my use case, I have to delete some objects from localStorage in a loop. Here is my code,

for (var i = 0; i < objectKeys.length; i++) {
  chrome.storage.local.remove(objectKeys[i], function() {
    // Do something with objectKeys[i] like remove the corresponding element from DOM
    // Show notification to user that objectKeys[i] item has been removed
  });
}

You can see I have used Closure here to identify which particular object was removed and do something with it later. But the issue is

It is possible that when anonymous method (remove success handler) will be called till then value of i might have changed in the loop and it affects the action in the handler.

How do I solve this problem ?

Sachin Jain
  • 21,353
  • 33
  • 103
  • 168
  • possible duplicate of [Javascript closure inside loops - simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Felix Kling Mar 07 '14 at 17:34
  • Probably one of the top 10 most common questions. – Felix Kling Mar 07 '14 at 17:38
  • 1
    @Felix thanks for posting the link to a much insightful answer..btw i did google search but related to ajax and loop terms.. Thanks once again.....time to pick up the good parts book and read about closure..:) – Sachin Jain Mar 08 '14 at 01:23

2 Answers2

1

We can use a recursive function instead of a for loop

var len = objectKeys.length;

function asyncLoop(count) {
  chrome.storage.local.remove(objectKeys[count], function() {
    if(count < len) { 
      asyncLoop(count++); 
    }
  });
}

asyncLoop(0);
Rob Sedgwick
  • 5,216
  • 4
  • 20
  • 36
  • +1 Good idea indeed!! I thought the same but issue with this approach is we have chained all the async calls and if one of them fails..Rest are not executed. – Sachin Jain Mar 07 '14 at 16:35
  • Its fine..I am good with the above approach..I will accept the answer as soon as SO permits me :) – Sachin Jain Mar 07 '14 at 16:44
  • I have edited the code to make it more simpler. Can you please verify it. Feel free to revert the revision if I made any mistake. Thanks – Sachin Jain Mar 07 '14 at 16:47
0

Try using a variable in the scope of the closure, to be accessed later.

for (var i = 0; i < objectKeys.length; i++) {
  var myobject = objectKeys[i]; //this variable is in the scope of the closure
  chrome.storage.local.remove(myobject, function() {
    // Do something with objectKeys[i] like remove the corresponding element from DOM
    // Show notification to user that objectKeys[i] item has been removed
  });
}
problemPotato
  • 589
  • 3
  • 8
  • This doesn't solve the problem. It's the same thing, `myobject` will have the value of the last iteration when the first callback is executed. – Felix Kling Mar 07 '14 at 17:37