Search code examples
javascriptpromisees6-promise

JS: Executing events overlapping in time afteranother


I receive events on-the-fly in the correct order in which I want to process them after another (as well on-the-fly - so don't "store" them first).

The following example is not going to work as the function someEventOccured() could be called multiple times in a very close timespan. Thus, the execution of handleEvent would overlap in time (which I don't want). As I am writing to a file in handleEvent() I cannot have simultaneously execute the function and need to maintain the order...

async someEventOccured(data:string){
   await handleEvent(data);
}

I have already tried using .then() and storing the promise, however I have no idea how to wait for the previous .then() to finish...

Your help is very appreciated <3


Solution

  • The general approach is to have a shared promise to queue onto:

    let queue = Promise.resolve();
    function someEventOccured(data:string) {
      queue = queue.then(() => {
        return handleEvent(data);
      }).catch(err => {
        // ensure `queue` is never rejected or it'll stop processing events
        // …
      });
    }
    

    Of course, this does implicitly store the data events in the closures on the promise chain.