summaryrefslogtreecommitdiffstats
path: root/dom/network/tests/add_task.js
blob: 3028afdb75d7da0705280d08f387fad89dacce2d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Temporary implementation of add_task for mochitest-plain until bug 1078657 is
// implemented.
SimpleTest.waitForExplicitFinish();
(function(scope) {
  var pendingTasks = [];
  var pendingPromise = null;

  // Strict spawn function that takes a known generatorFunc and assumes that
  // every yielded value will be a Promise.  If nesting is desired, then yield*
  // should be used!
  function spawn(generatorFunc) {
    return new Promise(function(resolve, reject) {
      try {
        var iterator = generatorFunc();
      }
      catch (ex) {
        ok(false, 'Problem invoking generator func: ' + ex + ': ' + ex.stack);
        return;
      }
      var stepResolved = function(result) {
        try {
          var iterStep = iterator.next(result);
        }
        catch (ex) {
          ok(false, 'Problem invoking iterator step: ' + ex + ': ' + ex.stack);
          return;
        }
        if (iterStep.done) {
          resolve(iterStep.value);
          return;
        }
        if (!iterStep.value || !iterStep.value.then) {
          ok(false, 'Iterator step returned non-Promise: ' + iterStep.value);
        }
        iterStep.value.then(stepResolved, generalErrback);
      };
      stepResolved();
    });
  }

  function maybeSpawn(promiseOrGenerator) {
    if (promiseOrGenerator.then) {
      return promiseOrGenerator;
    }
    return spawn(promiseOrGenerator);
  }

  scope.add_task = function(thing) {
    pendingTasks.push(thing);
  };

  function generalErrback(ex) {
    ok(false,
       'A rejection happened: ' +
       (ex ? (ex + ': ' + ex.stack) : ''));
  }

  function runNextTask() {
    if (pendingTasks.length) {
      pendingPromise = maybeSpawn(pendingTasks.shift());
      pendingPromise.then(runNextTask, generalErrback);
    } else {
      SimpleTest.finish();
    }
  }

  // Trigger runNextTask after we think all JS files have been loaded.
  // The primary goal is that we can call SimpleTest.finish() after all test
  // code has been loaded and run.  We gate this based on the document's
  // readyState.
  var running = false;
  function maybeStartRunning() {
    if (!running && document.readyState === 'complete') {
      running = true;
      document.removeEventListener('readystateChange', maybeStartRunning);
      // Defer to a subsequent turn of the event loop to let micro-tasks and any
      // other clever setTimeout(0) instances run first.
      window.setTimeout(runNextTask, 0);
    }
  }
  document.addEventListener('readystatechange', maybeStartRunning);
  maybeStartRunning();
})(this);