I'm creating an Action handler in NgXS (state management using NgRx under the hood).
Assuming that the action will be dispatched multiple times in short time period - is there a chance that more than one execution will reach doAsyncStuff()
method before the first one finishes it? To be more specific - can the execution of the code be interrupted between 3rd and 4th line by another execution, so both threads will pass the 'if' check? getState and setState methods are synchronous.
@Action(ExampleAction)
public async handleAction(ctx: StateContext<StateModel>) {
if (ctx.getState().state !== 'loading') {
ctx.setState(produce(ctx.getState(), (model: StateModel) => {model.state = 'loading';}));
try {
await doAsyncStuff();
model.state = 'success';
} catch (e) {
model.state = 'error';
}
}
}
I've read some answers regarding multiple threads in JS and some of them suggest that synchronous part will never be interupted in JS, but I also fount this: How to synchronize access to private members of a javascript object
"First, ECMAScript doesn't require JS to be executed in a single thread. Second, setTimeout() etc. are specified by HTML5 where it is clearly defined that the handler can indeed run in a parallel thread: html.spec.whatwg.org/multipage/infrastructure.html#in-parallel"
I'd like to know if it's possible that the execution of the code be interrupted between 3rd and 4th line and if it is a real possibility with most common browsers.