Sachin Jain
Sachin Jain

Reputation: 21842

How to perform an async operation in loop

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 ?

Upvotes: 0

Views: 109

Answers (2)

Rob Sedgwick
Rob Sedgwick

Reputation: 5226

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);

Upvotes: 1

problemPotato
problemPotato

Reputation: 609

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
  });
}

Upvotes: 0

Related Questions