Bug 1354884 - convert uses of 'defer' to 'new Promise' in client/webaudioeditor r=nchevobbe
authorMichael Kohler <mkohler@picobudget.com>
Sun, 09 Apr 2017 12:48:14 +0200
changeset 359781 61018db8d66ea9f098293fb3291cfffd013faf4c
parent 359780 6b8c59fc67a45fe7698e12b5d5a462b3cbb7e1b7
child 359782 c34ff92df5c30bab05cdf834663c502e140555c2
push id31857
push userphilringnalda@gmail.com
push dateSun, 21 May 2017 20:00:29 +0000
treeherdermozilla-central@cf9f9525e4d1 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersnchevobbe
bugs1354884
milestone55.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1354884 - convert uses of 'defer' to 'new Promise' in client/webaudioeditor r=nchevobbe MozReview-Commit-ID: 6duPsVQYGnT
devtools/client/webaudioeditor/test/browser_wa_properties-view-media-nodes.js
devtools/client/webaudioeditor/test/head.js
--- a/devtools/client/webaudioeditor/test/browser_wa_properties-view-media-nodes.js
+++ b/devtools/client/webaudioeditor/test/browser_wa_properties-view-media-nodes.js
@@ -13,30 +13,28 @@ function waitForDeviceClosed() {
 
   let temp = {};
   Cu.import("resource:///modules/webrtcUI.jsm", temp);
   let webrtcUI = temp.webrtcUI;
 
   if (!webrtcUI.showGlobalIndicator)
     return Promise.resolve();
 
-  let deferred = Promise.defer();
-
-  const message = "webrtc:UpdateGlobalIndicators";
-  let ppmm = Cc["@mozilla.org/parentprocessmessagemanager;1"]
-               .getService(Ci.nsIMessageBroadcaster);
-  ppmm.addMessageListener(message, function listener(aMessage) {
-    info("Received " + message + " message");
-    if (!aMessage.data.showGlobalIndicator) {
-      ppmm.removeMessageListener(message, listener);
-      deferred.resolve();
-    }
+  return new Promise((resolve, reject) => {
+    const message = "webrtc:UpdateGlobalIndicators";
+    let ppmm = Cc["@mozilla.org/parentprocessmessagemanager;1"]
+                 .getService(Ci.nsIMessageBroadcaster);
+    ppmm.addMessageListener(message, function listener(aMessage) {
+      info("Received " + message + " message");
+      if (!aMessage.data.showGlobalIndicator) {
+        ppmm.removeMessageListener(message, listener);
+        resolve();
+      }
+    });
   });
-
-  return deferred.promise;
 }
 
 add_task(function* () {
   let { target, panel } = yield initWebAudioEditor(MEDIA_NODES_URL);
   let { panelWin } = panel;
   let { gFront, $, $$, EVENTS, PropertiesView } = panelWin;
   let gVars = PropertiesView._propsView;
 
--- a/devtools/client/webaudioeditor/test/head.js
+++ b/devtools/client/webaudioeditor/test/head.js
@@ -7,17 +7,16 @@ var { classes: Cc, interfaces: Ci, utils
 var { require } = Cu.import("resource://devtools/shared/Loader.jsm", {});
 var { Task } = require("devtools/shared/task");
 var Services = require("Services");
 var { gDevTools } = require("devtools/client/framework/devtools");
 var { TargetFactory } = require("devtools/client/framework/target");
 var { DebuggerServer } = require("devtools/server/main");
 var { generateUUID } = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator);
 
-var Promise = require("promise");
 var Services = require("Services");
 var { WebAudioFront } = require("devtools/shared/fronts/webaudio");
 var DevToolsUtils = require("devtools/shared/DevToolsUtils");
 var flags = require("devtools/shared/flags");
 var audioNodes = require("devtools/server/actors/utils/audionodes.json");
 var mm = null;
 
 const FRAME_SCRIPT_UTILS_URL = "chrome://devtools/content/shared/frame-script-utils.js";
@@ -60,70 +59,67 @@ registerCleanupFunction(() => {
 function loadFrameScripts() {
   mm = gBrowser.selectedBrowser.messageManager;
   mm.loadFrameScript(FRAME_SCRIPT_UTILS_URL, false);
 }
 
 function addTab(aUrl, aWindow) {
   info("Adding tab: " + aUrl);
 
-  let deferred = Promise.defer();
   let targetWindow = aWindow || window;
   let targetBrowser = targetWindow.gBrowser;
 
   targetWindow.focus();
   let tab = targetBrowser.selectedTab = targetBrowser.addTab(aUrl);
   let linkedBrowser = tab.linkedBrowser;
 
-  BrowserTestUtils.browserLoaded(linkedBrowser).then(function () {
-    info("Tab added and finished loading: " + aUrl);
-    deferred.resolve(tab);
+  return new Promise((resolve, reject) => {
+    BrowserTestUtils.browserLoaded(linkedBrowser).then(function () {
+      info("Tab added and finished loading: " + aUrl);
+      resolve(tab);
+    });
   });
-
-  return deferred.promise;
 }
 
 function removeTab(aTab, aWindow) {
   info("Removing tab.");
 
-  let deferred = Promise.defer();
   let targetWindow = aWindow || window;
   let targetBrowser = targetWindow.gBrowser;
   let tabContainer = targetBrowser.tabContainer;
 
-  tabContainer.addEventListener("TabClose", function (aEvent) {
-    info("Tab removed and finished closing.");
-    deferred.resolve();
-  }, {once: true});
+  return new Promise((resolve, reject) => {
+    tabContainer.addEventListener("TabClose", function (aEvent) {
+      info("Tab removed and finished closing.");
+      resolve();
+    }, {once: true});
 
-  targetBrowser.removeTab(aTab);
-  return deferred.promise;
+    targetBrowser.removeTab(aTab);
+  });
 }
 
 function once(aTarget, aEventName, aUseCapture = false) {
   info("Waiting for event: '" + aEventName + "' on " + aTarget + ".");
 
-  let deferred = Promise.defer();
-
-  for (let [add, remove] of [
-    ["on", "off"], // Use event emitter before DOM events for consistency
-    ["addEventListener", "removeEventListener"],
-    ["addListener", "removeListener"]
-  ]) {
-    if ((add in aTarget) && (remove in aTarget)) {
-      aTarget[add](aEventName, function onEvent(...aArgs) {
-        aTarget[remove](aEventName, onEvent, aUseCapture);
-        info("Got event: '" + aEventName + "' on " + aTarget + ".");
-        deferred.resolve(...aArgs);
-      }, aUseCapture);
-      break;
+  return new Promise((resolve, reject) => {
+    for (let [add, remove] of [
+      ["on", "off"], // Use event emitter before DOM events for consistency
+      ["addEventListener", "removeEventListener"],
+      ["addListener", "removeListener"]
+    ]) {
+      if ((add in aTarget) && (remove in aTarget)) {
+        aTarget[add](aEventName, function onEvent(...aArgs) {
+          aTarget[remove](aEventName, onEvent, aUseCapture);
+          info("Got event: '" + aEventName + "' on " + aTarget + ".");
+          resolve(...aArgs);
+        }, aUseCapture);
+        break;
+      }
     }
-  }
-
-  return deferred.promise;
+  });
 }
 
 function reload(aTarget, aWaitForTargetEvent = "navigate") {
   aTarget.activeTab.reload();
   return once(aTarget, aWaitForTargetEvent);
 }
 
 function navigate(aTarget, aUrl, aWaitForTargetEvent = "navigate") {
@@ -201,59 +197,61 @@ function teardown(aTarget) {
 // and we can't yield them in a chain without missing actors, this allows
 // us to listen for `n` events and return a promise resolving to them.
 //
 // Takes a `front` object that is an event emitter, the number of
 // programs that should be listened to and waited on, and an optional
 // `onAdd` function that calls with the entire actors array on program link
 function getN(front, eventName, count, spread) {
   let actors = [];
-  let deferred = Promise.defer();
   info(`Waiting for ${count} ${eventName} events`);
-  front.on(eventName, function onEvent(...args) {
-    let actor = args[0];
-    if (actors.length !== count) {
-      actors.push(spread ? args : actor);
-    }
-    info(`Got ${actors.length} / ${count} ${eventName} events`);
-    if (actors.length === count) {
-      front.off(eventName, onEvent);
-      deferred.resolve(actors);
-    }
+
+  return new Promise((resolve, reject) => {
+    front.on(eventName, function onEvent(...args) {
+      let actor = args[0];
+      if (actors.length !== count) {
+        actors.push(spread ? args : actor);
+      }
+      info(`Got ${actors.length} / ${count} ${eventName} events`);
+      if (actors.length === count) {
+        front.off(eventName, onEvent);
+        resolve(actors);
+      }
+    });
   });
-  return deferred.promise;
 }
 
 function get(front, eventName) { return getN(front, eventName, 1); }
 function get2(front, eventName) { return getN(front, eventName, 2); }
 function get3(front, eventName) { return getN(front, eventName, 3); }
 function getSpread(front, eventName) { return getN(front, eventName, 1, true); }
 function get2Spread(front, eventName) { return getN(front, eventName, 2, true); }
 function get3Spread(front, eventName) { return getN(front, eventName, 3, true); }
 function getNSpread(front, eventName, count) { return getN(front, eventName, count, true); }
 
 /**
  * Waits for the UI_GRAPH_RENDERED event to fire, but only
  * resolves when the graph was rendered with the correct count of
  * nodes and edges.
  */
 function waitForGraphRendered(front, nodeCount, edgeCount, paramEdgeCount) {
-  let deferred = Promise.defer();
   let eventName = front.EVENTS.UI_GRAPH_RENDERED;
   info(`Wait for graph rendered with ${nodeCount} nodes, ${edgeCount} edges`);
-  front.on(eventName, function onGraphRendered(_, nodes, edges, pEdges) {
-    let paramEdgesDone = paramEdgeCount != null ? paramEdgeCount === pEdges : true;
-    info(`Got graph rendered with ${nodes} / ${nodeCount} nodes, ` +
-         `${edges} / ${edgeCount} edges`);
-    if (nodes === nodeCount && edges === edgeCount && paramEdgesDone) {
-      front.off(eventName, onGraphRendered);
-      deferred.resolve();
-    }
+
+  return new Promise((resolve, reject) => {
+    front.on(eventName, function onGraphRendered(_, nodes, edges, pEdges) {
+      let paramEdgesDone = paramEdgeCount != null ? paramEdgeCount === pEdges : true;
+      info(`Got graph rendered with ${nodes} / ${nodeCount} nodes, ` +
+           `${edges} / ${edgeCount} edges`);
+      if (nodes === nodeCount && edges === edgeCount && paramEdgesDone) {
+        front.off(eventName, onGraphRendered);
+        resolve();
+      }
+    });
   });
-  return deferred.promise;
 }
 
 function checkVariableView(view, index, hash, description = "") {
   info("Checking Variable View");
   let scope = view.getScopeAtIndex(index);
   let variables = Object.keys(hash);
 
   // If node shouldn't display any properties, ensure that the 'empty' message is
@@ -285,49 +283,48 @@ function checkVariableView(view, index, 
     else {
       is(value, hash[variable],
         "Correct property value of " + hash[variable] + " for " + variable + " " + description);
     }
   });
 }
 
 function modifyVariableView(win, view, index, prop, value) {
-  let deferred = Promise.defer();
   let scope = view.getScopeAtIndex(index);
   let aVar = scope.get(prop);
   scope.expand();
 
-  win.on(win.EVENTS.UI_SET_PARAM, handleSetting);
-  win.on(win.EVENTS.UI_SET_PARAM_ERROR, handleSetting);
+  return new Promise((resolve, reject) => {
+    win.on(win.EVENTS.UI_SET_PARAM, handleSetting);
+    win.on(win.EVENTS.UI_SET_PARAM_ERROR, handleSetting);
 
-  // Focus and select the variable to begin editing
-  win.focus();
-  aVar.focus();
-  EventUtils.sendKey("RETURN", win);
+    // Focus and select the variable to begin editing
+    win.focus();
+    aVar.focus();
+    EventUtils.sendKey("RETURN", win);
 
-  // Must wait for the scope DOM to be available to receive
-  // events
-  executeSoon(() => {
-    info("Setting " + value + " for " + prop + "....");
-    for (let c of (value + "")) {
-      EventUtils.synthesizeKey(c, {}, win);
-    }
-    EventUtils.sendKey("RETURN", win);
-  });
+    // Must wait for the scope DOM to be available to receive
+    // events
+    executeSoon(() => {
+      info("Setting " + value + " for " + prop + "....");
+      for (let c of (value + "")) {
+        EventUtils.synthesizeKey(c, {}, win);
+      }
+      EventUtils.sendKey("RETURN", win);
+    });
 
-  function handleSetting(eventName) {
-    win.off(win.EVENTS.UI_SET_PARAM, handleSetting);
-    win.off(win.EVENTS.UI_SET_PARAM_ERROR, handleSetting);
-    if (eventName === win.EVENTS.UI_SET_PARAM)
-      deferred.resolve();
-    if (eventName === win.EVENTS.UI_SET_PARAM_ERROR)
-      deferred.reject();
-  }
-
-  return deferred.promise;
+    function handleSetting(eventName) {
+      win.off(win.EVENTS.UI_SET_PARAM, handleSetting);
+      win.off(win.EVENTS.UI_SET_PARAM_ERROR, handleSetting);
+      if (eventName === win.EVENTS.UI_SET_PARAM)
+        resolve();
+      if (eventName === win.EVENTS.UI_SET_PARAM_ERROR)
+        reject();
+    }
+  });
 }
 
 function findGraphEdge(win, source, target, param) {
   let selector = ".edgePaths .edgePath[data-source='" + source + "'][data-target='" + target + "']";
   if (param) {
     selector += "[data-param='" + param + "']";
   }
   return win.document.querySelector(selector);
@@ -355,29 +352,28 @@ function command(button) {
 function isVisible(element) {
   return !element.getAttribute("hidden");
 }
 
 /**
  * Used in debugging, returns a promise that resolves in `n` milliseconds.
  */
 function wait(n) {
-  let { promise, resolve } = Promise.defer();
-  setTimeout(resolve, n);
-  info("Waiting " + n / 1000 + " seconds.");
-  return promise;
+  return new Promise((resolve, reject) => {
+    setTimeout(resolve, n);
+    info("Waiting " + n / 1000 + " seconds.");
+  });
 }
 
 /**
  * Clicks a graph node based on actorID or passing in an element.
  * Returns a promise that resolves once UI_INSPECTOR_NODE_SET is fired and
  * the tabs have rendered, completing all RDP requests for the node.
  */
 function clickGraphNode(panelWin, el, waitForToggle = false) {
-  let { promise, resolve } = Promise.defer();
   let promises = [
     once(panelWin, panelWin.EVENTS.UI_INSPECTOR_NODE_SET),
     once(panelWin, panelWin.EVENTS.UI_PROPERTIES_TAB_RENDERED),
     once(panelWin, panelWin.EVENTS.UI_AUTOMATION_TAB_RENDERED)
   ];
 
   if (waitForToggle) {
     promises.push(once(panelWin, panelWin.EVENTS.UI_INSPECTOR_TOGGLED));
@@ -477,36 +473,34 @@ function waitForInspectorRender(panelWin
   ]);
 }
 
 /**
  * Takes a string `script` and evaluates it directly in the content
  * in potentially a different process.
  */
 function evalInDebuggee(script) {
-  let deferred = Promise.defer();
-
   if (!mm) {
     throw new Error("`loadFrameScripts()` must be called when using MessageManager.");
   }
 
-  let id = generateUUID().toString();
-  mm.sendAsyncMessage("devtools:test:eval", { script: script, id: id });
-  mm.addMessageListener("devtools:test:eval:response", handler);
+  return new Promise((resolve, reject) => {
+    let id = generateUUID().toString();
+    mm.sendAsyncMessage("devtools:test:eval", { script: script, id: id });
+    mm.addMessageListener("devtools:test:eval:response", handler);
 
-  function handler({ data }) {
-    if (id !== data.id) {
-      return;
-    }
+    function handler({ data }) {
+      if (id !== data.id) {
+        return;
+      }
 
-    mm.removeMessageListener("devtools:test:eval:response", handler);
-    deferred.resolve(data.value);
-  }
-
-  return deferred.promise;
+      mm.removeMessageListener("devtools:test:eval:response", handler);
+      resolve(data.value);
+    }
+  });
 }
 
 /**
  * Takes an AudioNode type and returns it's properties (from audionode.json)
  * as keys and their default values as keys
  */
 function nodeDefaultValues(nodeName) {
   let fn = NODE_CONSTRUCTORS[nodeName];