title: How to serialize execution of functions in a class (JS/TS) - a "QueueManager"?
body: <p>I have a single class in TS that operates with local storage (namely PouchDB) - the basic idea is to wrap the storing of objects so the rest of the app doesn't have to worry about it (and to be able to easily switch it out if need be).</p>
  
  <p>The functions are for example:</p>
  
  <pre><code>public addOrUpdateBulk(myValues: Array&lt;DbEntryType&gt;): Promise&lt;boolean&gt;{
      //call into pouchdb saving (which does this asynchronously)
  }
  public getById(id: number): Promise&lt;DbEntryType&gt; {
     //get the value from pouchdb...
  }
  </code></pre>
  
  <p>The issue I'm facing can be best described as loss of "<strong><em>read-your-writes</em></strong>" consistency - i.e. the caller has to do the work and chain the writes and reads in order to get the expected results. I can't go into details of the thousands of lines of code, this is just an oversimplification of the issue, but it best describes the problem (there's actually all sorts of reads and writes from all over the place, and not by only one 'data owner', and this throws conflicts in updates). Yes, this could be resolved by being careful but I'm looking for a way to solve this in one class and for everybody.</p>
  
  <p>I'm looking for a design so that all of the methods that get called are executed in order of calling. Sure, this slows down everything dramatically, but for now lets assume that's not an issue. </p>
  
  <p>What I'm thinking of is something like this:</p>
  
  <pre><code>public addOrUpdateBulk(myValues: Array&lt;DbEntryType&gt;, isInQueue: boolean = false): Promise&lt;any&gt;{
      if (isInQueue){
          return call_to_pouchdb_func(...)...
      }
      else{
          return QueueManager.enqueue("writer", addOrUpdateBulk, myValues, true);
      }
  }
  
  public getById(id: number, isInQueue: boolean = false): Promise&lt;DbEntryType&gt; {
  
     if (isInQueue || !QueueManager.hasAny("writer")){ //no need to queue reads if no writes are going on
          return call_to_pouchdb_func(...)...
      }
      else {
          return QueueManager.enqueue("reader", getById, number, true);
      }
  }
  </code></pre>
  
  <p>About designing the <code>QueueManager</code> I'm at a miss: </p>
  
  <ol>
  <li>How to write the <code>enqueue</code> function to eventually execute the method with unknown number of arguments?</li>
  <li>What to use as queuing mechanism? The async.js has neat "queue" that looks promising, but since I'm in angular2, maybe chain into Observables? How?</li>
  <li>The returning of values to the caller is the main "pain-point" I don't see a solution for... any ideas?</li>
  </ol>