0

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.

  • 1
    Today's browsers don't use parallelism as defined in the spec. (I'm not aware of a javascript engine that does implement parallelism but they might exist.) They do have multiple execution contexts, such as the page or a webworker, but those contexts only effect each other through the event system: One context sends a message to another which then receives the message as part of an event. As far as your question, as long as you're using Node or a browser to execute JS, you can treat them as cooperative multitasking: Only one thing is ever running and control is voluntarily yielded via `await`. – Ouroborus Sep 26 '22 at 20:16

0 Answers0