title: Wait and don't execute a function until a light is set to green
body: <p>I understand that we could use <code>.then</code> to make sure the order of asynchronous calls:</p>
  
  <pre><code>return doTask1()
      .then(function () {
          return doTask2()
      })
  </code></pre>
  
  <p>But sometimes it will be convenient to have a light and to be able to say: <strong>wait and don't execute task2 until a light is set to GREEN</strong>; the light is a variable initially set to RED, and can be set to GREEN by task1 or other functions.</p>
  
  <p>Does anyone know if it is possible to accomplish this?</p>
  
  <p><strong>Edit 1:</strong> I think being able to express this is particularly useful when <strong>we need several tasks to be ended to set the light green, and we don't know/mind the order of these tasks</strong>. <code>.then</code> cannot do this easily, because we don't know the order of these tasks.</p>
  
  <p><strong>Edit 2:</strong> Regarding <code>my light</code>, I had asked <a href="https://stackoverflow.com/q/42702333/702977">a more specific question</a>. In one word, it is the message another application B sends by <code>postMessage</code> that we are waiting for. At the moment, I have written the following code (which is in a <code>resolve</code>), which works more or less (I have not tried if making only ONE function with their common part will work).</p>
  
  <pre><code>task1: ['codeService', '$window', '$q', function (codeService, $window, $q) {
      return codeService.task1().then(function () { // task1 sends a request to another application B by postMessage
          var deferred = $q.defer();
          $window.addEventListener("message", function (event) {
              if (event.data.req === "task1ReturnFromB") deferred.resolve(event.data)
          }, { once: true });
          return deferred.promise
      })
  }],
  task2: ['codeService', 'task1', '$window', '$q', function(codeService, task1, $window, $q) {
      return codeService.task2().then(function () { // task2 sends a request to Application B by postMessage
          var deferred = $q.defer();
          $window.addEventListener("message", function (event) {
              if (event.data.req === "task2ReturnFromB") deferred.resolve(event.data) 
          }, { once: true });
          return deferred.promise
      })
  }]
  </code></pre>
  
  <p>So in this specific case, <code>postMessage</code> sent by Application B triggers the event. In a more general case, I guess we could probably trigger an event by eg, <a href="https://stackoverflow.com/a/2490876/702977">dispatchEvent</a>, in one application?</p>