summaryrefslogtreecommitdiffstats
path: root/dom/tests/mochitest/fetch/utils.js
blob: 8b93c1e90bad5e9ed5d008469b720c5d23ee2a01 (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
// Utilities
// =========

// Helper that uses FileReader or FileReaderSync based on context and returns
// a Promise that resolves with the text or rejects with error.
function readAsText(blob) {
  if (typeof FileReader !== "undefined") {
    return new Promise(function (resolve, reject) {
      var fs = new FileReader();
      fs.onload = function () {
        resolve(fs.result);
      };
      fs.onerror = reject;
      fs.readAsText(blob);
    });
  } else {
    var fs = new FileReaderSync();
    return Promise.resolve(fs.readAsText(blob));
  }
}

function readAsArrayBuffer(blob) {
  if (typeof FileReader !== "undefined") {
    return new Promise(function (resolve, reject) {
      var fs = new FileReader();
      fs.onload = function () {
        resolve(fs.result);
      };
      fs.onerror = reject;
      fs.readAsArrayBuffer(blob);
    });
  } else {
    var fs = new FileReaderSync();
    return Promise.resolve(fs.readAsArrayBuffer(blob));
  }
}

function waitForState(worker, state, context) {
  return new Promise(resolve => {
    if (worker.state === state) {
      resolve(context);
      return;
    }
    worker.addEventListener("statechange", function onStateChange() {
      if (worker.state === state) {
        worker.removeEventListener("statechange", onStateChange);
        resolve(context);
      }
    });
  });
}