Search code examples
javascripteventslanguage-agnostic

running code when two events have triggered


This is mostly a language-agnostic question.

If I'm waiting for two events to complete (say, two IO events or http requests), what is the best pattern to deal with this. One thing I can think of is the following (pseudo js example).

request1.onComplete = function() {
  req1Completed = true;
  eventsCompleted();
}

request2.onComplete = function() {
  req2Completed = true;
  eventsCompleted();
}

eventsCompleted = function() {

  if (!req1Completed || !req2Completed) return;
  // do stuff

}

Is this the most effective pattern, or are there more elegant ways to solve this issue?


Solution

  • Before even going into the details, here's something neat that takes advantage of lambda functions off the top of my head:

    function makeCountdownCallback(count, callback) {
        return function() {
            if (--count == 0)
                callback();
        };
    }
    
    request1.onComplete = request2.onComplete = makeCountdownCallback(2, function() {
        // do stuff
    });
    

    This obviously assumes that each event fires at most once, and doesn't take advantage of order.