lissajous
lissajous

Reputation: 451

Ensure angular service logic does not run twice for user

I have service in Angular 12, TypeScript 4.3.5

//...
@Injectable({
  providedIn: 'root'
})
export class SessionService {
  constructor(
    private lsService: LocalStorageService) {
    }

  getSessionId(): string {
    let userId= this.lsService.get('key');
    if (!userId) {
      userId = this.getRandomId(); // assign new identifier
      this.lsService.set('key', userId);
    }

    return userId;
  }
//...

I am afraid there may be a situation where userId may be set twice and sb will read the first set value before 2nd is set.

Questions:

  1. Is this possible?
  2. How to guarantee this won't happen (without 3rd party libraries)?

Upvotes: 0

Views: 31

Answers (1)

Petr Averyanov
Petr Averyanov

Reputation: 9476

In 'normal' JS (e.g. no service workers) you have only one thread. And you never face issues like e.g. in Java or other multi-thread language.

So you can be quite sure that it will never happen.

You can try something like and see that methods never collide:

function test() {
  for (let i = 0; i < 10000; i++) {
    window.testVar++;
  }
  for (let i = 0; i < 10000; i++) {
    window.testVar--;
  }
  console.log(window.testVar);
}

window.testVar = 0;
for (let i = 0; i < 1000; i++) {
  setTimeout(test, Math.random() * 1000)
}

No matter what numbers u put here u will never see non-zero output.

Upvotes: 1

Related Questions