Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when two async functions modify the same object in Javascript?

Related to:
What happens when two javascript events try to modify same variable at the same time

But asking here because that's an old question, now we have Promises and "await" and I think could be a problem:

https://jsfiddle.net/d6k2gLu7/

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms)); 
}

setTimeout(async function(){
   globalArray.push(1);
   await sleep(100); 
   globalArray.push(2);
     printArray();
}, 500);

setTimeout(function(){
   globalArray.push(3);
   printArray();
}, 500);

Without the sleep that will be 1,2,3 but with sleep in the middle it ends with 1,3,2

So we need to check again all the "global objects" after some "await"? (I'm starting to understand why is so important to use pure functions)

like image 920
Enrique Avatar asked Jul 25 '26 13:07

Enrique


1 Answers

Javascript is still single threaded. Therefore, there are no "thread safety" issues (e.g. 2 threads writing to the same memory location). On the other hand, Javascript functions may be executed asynchronously. Therefore, when executing several asynchronous functions, there is no guarantee to the order and when each function will start or finish (unless you use "await" and/or "then" before calling the next function).

There is a tendency to confuse between asynchronous code (for "efficiency") and multi-threaded code (for "scalability"). But really, it has two different purposes. Too many times I've observed developers adding "threads" to make their code more "efficient" (especially in Java/C++), but that's a common mistake. In many cases adding threads will not improve the efficiency of the code. (E.g. create a thread pool with 20 threads to send and handle http requests/responses concurrently).

Scalable software should often use both. Javascript, is not intended to be scalable, but definitely efficient (send and handle 20 http requests/responses concurrently works rather well in Javascript).

like image 60
Tomer Avatar answered Jul 28 '26 03:07

Tomer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!