Sequenced calls of afterSave

I have a data consistency problem, my afterSave trigger does many operations (a few database calls in a row) and I don’t want it to be interrupted by a call of afterSave from another record.

Sample:
I would like it to go like that:

  1. 1st record after save - gets something from DB
  2. 1st record after save - gets something from DB
    3 )1st record after save - saves something to DB
    — here I imaging some lock is unlocked and second after save can be called
  3. 2nd record after save - gets something from DB
  4. 2nd record after save - gets something from DB
  5. 2nd record after save - saves something to DB

Sample of the wrong sequence

  1. 1st record after save - gets something from DB
  2. 2nd record after save - gets something from DB
    3 )2nd record after save - gets something to DB
  3. 2nd record after save - saves something from DB
  4. 1st record after save - gets something from DB
  5. 1st record after save - saves something to DB

I’m not very experienced in JS.
Is there any way like using semaphore that will stop going into AfterSave of specific Collection of 2 or more records at the same time? Simply: one call of AfterSave and then we can do another call of AfterSave.

Would you mind to share a code that reproduces your issue? Basically if your 2nd record afterSave trigger returns a Promise, and you use await secondObject.save() on your 1st record afterSave, 1st record should wait for 2nd record afterSave to complete.

Actually I don’t have code ready.
Simply I want to have a few awaits in a row in afterSave.
I understand that Node js works that when I’m waiting on await, in that time other afterSave can be called so in the middle of one afterSave, another afterSave will start (from other record). I would like to have kind of Semaphore on the beginning of afterSave and release it on the end.
I think I’m going to change it into a job which will just operate in a loop and sequencely do what I wanted to do in afterSave.

That sounds like a plan.