0

In a scenario where I have 2 buttons, but_A and but_B.

but_A.onMouseClicked(chrome.storage.local.set({"key": "A"}, function(){
                console.log("but_A val set"); }));

but_A.onMouseClicked(chrome.storage.local.set({"key": "B"}, function(){
                console.log("but_B val set"); }));

If I click but_A, then but_B, what will the value corresponding to "key" be? Will the behaviour be deterministic?

I reasoned so far that: when A is pressed, the first chrome.storage.local.set() will enter the message queue, popped to stack and execute. While the .set() for A is still executing, B is pressed. The .set() for B will also execute. Will the two chrome.storage.local.set() run simultaneously on two separate threads?

Thank you!

Osadhi Virochana
  • 1,294
  • 2
  • 11
  • 21
Ella Yang
  • 1
  • 2

1 Answers1

0

All code, functions, callbacks, events, microtasks, and so on in a given execution environment in JavaScript will be processed sequentially using the event loop. There are no threads.

However, the extension API documentation doesn't guarantee the order of actual work inside the API matches the order of invocation so even if the current implementation does it internally this is not something you should rely upon.

You can chain a Promise like this:

let setChain = Promise.resolve();
const set = data => {
  setChain = setChain.then(() => new Promise(resolve => {
    chrome.storage.local.set(data, resolve);
  }));
};

Now you can use it like set({foo: 1}); set({foo: 2});

wOxxOm
  • 65,848
  • 11
  • 132
  • 136
  • If the order is not deterministic, how would you suggest to achieve the following: The new tab page has an input field that takes in data. The user puts in data and hit a "save" button. Then the next time the user opens a new tab page, the data gets displayed. Wouldn't there always be a race condition between saving the data and accessing the data? – Ella Yang Jul 09 '20 at 17:58
  • It depends on how you access it. Inside the same tab during its single lifetime you can chain via Promise so it's not a problem. As for saving in one tab and reading in another tab, yes it's racy, but practically it's unlikely to happen because saving/reading is faster than creating a new tab. You can use a semaphore (mutex) to avoid the raciness in the second case though e.g. via a persistent background script and chrome.extension.getBackgroundPage. – wOxxOm Jul 09 '20 at 18:09