1

This is a part of my chrome extension, but the part that I'm not understanding is from javascript.

let elementsArray = [
    document.getElementById("main_keywords"),
    document.getElementById("search_side"), 
    document.getElementById("news_emotion"), 
    document.getElementById("news_comments")
];

for (elem of elementsArray) {
  var key = elem.getAttribute("id");

  chrome.storage.sync.set({ key: false }, function() {
      console.log(key + " saved : " + false);

      chrome.storage.sync.get({ key }, function (result) {
        console.log(key + " is " + result.key)
      });
  });
}

My intention was, for every element in elementsArray, it should set {key:false} to chrome.storage api using the id of the element. The result was that only the last element of elementsArray, which is news_comments, was saved 4 times. Console output is as below.

news_comments saved : false
news_comments saved : false
news_comments saved : false
news_comments saved : false
news_comments is false
news_comments is false
news_comments is false
news_comments is false

Chrome APIs are asynchronous but I don't have solid understanding on this concept although I'm not sure if this has to do with that.

isherwood
  • 58,414
  • 16
  • 114
  • 157

1 Answers1

1

Create a function and call it with argument which will save the key variable in its scope and will remember the value.

When your code using that variable is inside loop, your loop will end and the callbacks for get()are still pending (async callbacks). So when those callbacks will be executed, that key variable must have been updated to last value.

But when you move that code into a function, and call that function inside a loop. On every iteration, that function will be in invoked with a new value and that will remain for there for the code inside that function even value of passed variable outside has been updated but value passed to function will remain same due to scope of function. Read more about scopes in JavaScript.

const update = key => {
  chrome.storage.sync.set({ [key]: false }, function() {
      console.log(key + " saved : " + false);
      chrome.storage.sync.get({ key }, function (result) {
        console.log(key + " is " + result.key)
      });
  });
}
for (elem of elementsArray) {
  var key = elem.getAttribute("id");
  update(key);
}
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60