let mutableObject = {};
for( ...loop over wtv...) {
const res = await someAsyncFunc();
if(!mutable[res.someKey]) {
mutable[res.someKey] = {}
}
mutable[res.someKey][res.other] = res.value;
}
res.someKey is common to many res, the question is, is it possible at some point that mutable[res.someKey] is detected as empty and in fact it's being populated by another res in the loop. Which could result in a reset ( mutable[res.someKey] = {}) and skip the other populating res action.
in other word is this suit of event possible ?
=> loop1 !mutable[res.someKey] is empty ...
=> loop2 !mutable[res.someKey] is empty , lets reset and populate !
=> loop1 ... , lets reset and populate => we lose loop2 action with the reset
I think it's fine it would execute the totality of a loop before the next one but I have some doubts.
I hope it's clear enough let me know, thanks in advance.
It's not possible if I understood you correctly.
JavaScript is usually single threaded (there are exceptions, but you stated nothing specific so I assume there is nothing special in your case).
In JavaScript all code is executed inside of events. These events are queued into the event queue. The events from the queue are always executed completely before the next event in the queue is executed because there is only a single thread where they can be executed.
With async-await it is a bit harder to see from the code, but the pricipal still stays the same.
I always look at it like this:
async-await "cuts" the function into parts at the await
but the parts themselves are always execute in their entirety before anything else can happen.
When the function starts, the following code is executed without being able to be interrupted by a different event.
let mutableObject = {};
for( ...loop over wtv...) { // first iteration
someAsyncFunc(); // someAsyncFunc is executed but does not "return" yet
Then the first "event" is finished because of the await
.
When the returned Promise from someAsyncFunc() resolves. it will continue with:
const res = // result is written from someAsyncFunc
if(!mutable[res.someKey]) {
mutable[res.someKey] = {}
}
mutable[res.someKey][res.other] = res.value;
}
for( ...loop over wtv...) { // next iteration
someAsyncFunc();
And this part can also not be interrupted by different event, meaning that everything that happens between res
being set to the next call to someAsyncFunc() happens atomically.
Because of that, another loop cannot populate mutable[res.someKey]
during that time.
For further reading: