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 ?

3
  • possible duplicate of Javascript closure inside loops - simple practical example Commented Mar 7, 2014 at 17:34
  • Probably one of the top 10 most common questions. Commented Mar 7, 2014 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..:) Commented Mar 8, 2014 at 1:23

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

3 Comments

+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.
Its fine..I am good with the above approach..I will accept the answer as soon as SO permits me :)
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
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
  });
}

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.