Bug 1362882 - script-generated patch to switch from Promise.defer() to new Promise() where it's straightforward, rs=Mossop.

This commit is contained in:
Florian Quèze 2017-05-12 14:55:27 +02:00
parent 67e56b7404
commit 97f401c644
102 changed files with 2718 additions and 2718 deletions

View File

@ -66,7 +66,7 @@ var gTests = [
HTTPS_BASE + "healthreport_testRemoteCommands.html");
},
run(iframe) {
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
let results = 0;
try {
iframe.contentWindow.addEventListener("FirefoxHealthReportTestResponse", function evtHandler(event) {
@ -77,15 +77,15 @@ var gTests = [
} else if (data.type == "testsComplete") {
is(results, data.count, "Checking number of results received matches the number of tests that should have run");
iframe.contentWindow.removeEventListener("FirefoxHealthReportTestResponse", evtHandler, true);
deferred.resolve();
resolve();
}
}, true);
} catch (e) {
ok(false, "Failed to get all commands");
deferred.reject();
reject();
}
return deferred.promise;
});
}
},
@ -114,7 +114,7 @@ function test() {
}
function promiseNewTabLoadEvent(aUrl, aEventType = "load") {
let deferred = Promise.defer();
return new Promise(resolve => {
let tab = gBrowser.selectedTab = gBrowser.addTab(aUrl);
tab.linkedBrowser.addEventListener(aEventType, function(event) {
let iframe = tab.linkedBrowser.contentDocument.getElementById("remote-report");
@ -124,8 +124,8 @@ function promiseNewTabLoadEvent(aUrl, aEventType = "load") {
return;
}
iframe.removeEventListener("load", frameLoad);
deferred.resolve(iframe);
resolve(iframe);
});
}, {capture: true, once: true});
return deferred.promise;
});
}

View File

@ -28,19 +28,19 @@ function test() {
var zoomLevel = ZoomManager.zoom;
// Start the sub-document load.
let deferred = Promise.defer();
await new Promise(resolve => {
executeSoon(function() {
BrowserTestUtils.browserLoaded(testBrowser, true).then(url => {
is(url, TEST_IFRAME_URL, "got the load event for the iframe");
is(ZoomManager.zoom, zoomLevel, "zoom is retained after sub-document load");
FullZoomHelper.removeTabAndWaitForLocationChange().
then(() => deferred.resolve());
then(() => resolve());
});
ContentTask.spawn(testBrowser, TEST_IFRAME_URL, url => {
content.document.querySelector("iframe").src = url;
});
});
await deferred.promise;
});
})().then(finish, FullZoomHelper.failAndContinue(finish));
}

View File

@ -74,9 +74,9 @@ function testNavigation() {
}
function waitForNextTurn() {
let deferred = Promise.defer();
setTimeout(() => deferred.resolve(), 0);
return deferred.promise;
return new Promise(resolve => {
setTimeout(() => resolve(), 0);
});
}
var finishTestStarted = false;

View File

@ -386,16 +386,16 @@ add_task(async function cycleEngines() {
await msg("key", { key: "VK_DOWN", waitForSuggestions: true });
let promiseEngineChange = function(newEngineName) {
let deferred = Promise.defer();
return new Promise(resolve => {
Services.obs.addObserver(function resolver(subj, topic, data) {
if (data != "engine-current") {
return;
}
SimpleTest.is(subj.name, newEngineName, "Engine cycled correctly");
Services.obs.removeObserver(resolver, "browser-search-engine-modified");
deferred.resolve();
resolve();
}, "browser-search-engine-modified");
return deferred.promise;
});
}
let p = promiseEngineChange(TEST_ENGINE_PREFIX + " " + TEST_ENGINE_2_BASENAME);
@ -665,15 +665,15 @@ function msg(type, data = null) {
type,
data,
});
let deferred = Promise.defer();
return new Promise(resolve => {
gMsgMan.addMessageListener(TEST_MSG, function onMsg(msgObj) {
if (msgObj.data.type != type) {
return;
}
gMsgMan.removeMessageListener(TEST_MSG, onMsg);
deferred.resolve(msgObj.data.data);
resolve(msgObj.data.data);
});
});
return deferred.promise;
}
function checkState(actualState, expectedInputVal, expectedSuggestions,
@ -737,16 +737,16 @@ async function promiseTab() {
}
function promiseMsg(name, type, msgMan) {
let deferred = Promise.defer();
return new Promise(resolve => {
info("Waiting for " + name + " message " + type + "...");
msgMan.addMessageListener(name, function onMsg(msgObj) {
info("Received " + name + " message " + msgObj.data.type + "\n");
if (msgObj.data.type == type) {
msgMan.removeMessageListener(name, onMsg);
deferred.resolve(msgObj);
resolve(msgObj);
}
});
return deferred.promise;
});
}
function setUpEngines() {

View File

@ -20,14 +20,14 @@ add_task(async function test_remoteWebNavigation_postdata() {
let server = new obj.HttpServer();
server.start(-1);
let loadDeferred = Promise.defer();
await new Promise(resolve => {
server.registerPathHandler("/test", (request, response) => {
let body = obj.CommonUtils.readBytesFromInputStream(request.bodyInputStream);
is(body, "success", "request body is correct");
is(request.method, "POST", "request was a post");
response.write("Received from POST: " + body);
loadDeferred.resolve();
resolve();
});
let i = server.identity;
@ -41,10 +41,10 @@ add_task(async function test_remoteWebNavigation_postdata() {
openUILinkIn(path, "tab", null, makeInputStream(postdata));
await loadDeferred.promise;
});
await BrowserTestUtils.removeTab(gBrowser.selectedTab);
let serverStoppedDeferred = Promise.defer();
server.stop(function() { serverStoppedDeferred.resolve(); });
await serverStoppedDeferred.promise;
await new Promise(resolve => {
server.stop(function() { resolve(); });
});
});

View File

@ -19,27 +19,27 @@ var FormHistory = (Components.utils.import("resource://gre/modules/FormHistory.j
var Downloads = (Components.utils.import("resource://gre/modules/Downloads.jsm", {})).Downloads;
function promiseFormHistoryRemoved() {
let deferred = Promise.defer();
return new Promise(resolve => {
Services.obs.addObserver(function onfh() {
Services.obs.removeObserver(onfh, "satchel-storage-changed");
deferred.resolve();
resolve();
}, "satchel-storage-changed");
return deferred.promise;
});
}
function promiseDownloadRemoved(list) {
let deferred = Promise.defer();
return new Promise(resolve => {
let view = {
onDownloadRemoved(download) {
list.removeView(view);
deferred.resolve();
resolve();
}
};
list.addView(view);
return deferred.promise;
});
}
add_task(async function test() {
@ -50,7 +50,7 @@ add_task(async function test() {
});
function countEntries(name, message, check) {
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
var obj = {};
if (name !== null)
@ -59,18 +59,18 @@ function countEntries(name, message, check) {
let count;
FormHistory.count(obj, { handleResult: result => count = result,
handleError(error) {
deferred.reject(error)
reject(error)
throw new Error("Error occurred searching form history: " + error);
},
handleCompletion(reason) {
if (!reason) {
check(count, message);
deferred.resolve();
resolve();
}
},
});
return deferred.promise;
});
}
async function onHistoryReady() {
@ -445,7 +445,7 @@ async function onHistoryReady() {
}
function setupHistory() {
let deferred = Promise.defer();
return new Promise(resolve => {
let places = [];
@ -480,37 +480,37 @@ function setupHistory() {
PlacesUtils.asyncHistory.updatePlaces(places, {
handleError: () => ok(false, "Unexpected error in adding visit."),
handleResult: () => { },
handleCompletion: () => deferred.resolve()
handleCompletion: () => resolve()
});
return deferred.promise;
});
}
async function setupFormHistory() {
function searchEntries(terms, params) {
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
let results = [];
FormHistory.search(terms, params, { handleResult: result => results.push(result),
handleError(error) {
deferred.reject(error);
reject(error);
throw new Error("Error occurred searching form history: " + error);
},
handleCompletion(reason) { deferred.resolve(results); }
handleCompletion(reason) { resolve(results); }
});
});
return deferred.promise;
}
function update(changes) {
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
FormHistory.update(changes, { handleError(error) {
deferred.reject(error);
reject(error);
throw new Error("Error occurred searching form history: " + error);
},
handleCompletion(reason) { deferred.resolve(); }
handleCompletion(reason) { resolve(); }
});
});
return deferred.promise;
}
// Make sure we've got a clean DB to start with, then add the entries we'll be testing.

View File

@ -37,7 +37,7 @@ add_task(async function test_star_redirect() {
* Waits for the star to reflect the expected state.
*/
function promiseStarState(aValue) {
let deferred = Promise.defer();
return new Promise(resolve => {
let expectedStatus = aValue ? BookmarkingUI.STATUS_STARRED
: BookmarkingUI.STATUS_UNSTARRED;
(function checkState() {
@ -46,10 +46,10 @@ function promiseStarState(aValue) {
info("Waiting for star button change.");
setTimeout(checkState, 1000);
} else {
deferred.resolve();
resolve();
}
})();
return deferred.promise;
});
}
/**
@ -66,7 +66,7 @@ function promiseStarState(aValue) {
function promiseTabLoadEvent(aTab, aURL, aFinalURL) {
if (!aFinalURL)
aFinalURL = aURL;
let deferred = Promise.defer();
return new Promise(resolve => {
info("Wait for load tab event");
aTab.linkedBrowser.addEventListener("load", function load(event) {
if (event.originalTarget != aTab.linkedBrowser.contentDocument ||
@ -77,8 +77,8 @@ function promiseTabLoadEvent(aTab, aURL, aFinalURL) {
}
aTab.linkedBrowser.removeEventListener("load", load, true);
info("Tab load event received");
deferred.resolve();
resolve();
}, true, true);
aTab.linkedBrowser.loadURI(aURL);
return deferred.promise;
});
}

View File

@ -59,19 +59,19 @@ add_task(async function() {
// resolves promise when directory links are downloaded and written to disk
function watchLinksChangeOnce() {
let deferred = Promise.defer();
return new Promise(resolve => {
let observer = {
onManyLinksChanged: () => {
DirectoryLinksProvider.removeObserver(observer);
NewTabUtils.links.populateCache(() => {
NewTabUtils.allPages.update();
deferred.resolve();
resolve();
}, true);
}
};
observer.onDownloadFail = observer.onManyLinksChanged;
DirectoryLinksProvider.addObserver(observer);
return deferred.promise;
});
}
let gOrigDirectorySource = Services.prefs.getCharPref(PREF_NEWTAB_DIRECTORYSOURCE);

View File

@ -37,17 +37,17 @@ function closeAllNotifications() {
return Promise.resolve();
}
let deferred = Promise.defer();
return new Promise(resolve => {
for (let notification of notificationBox.allNotifications) {
waitForNotificationClose(notification, function() {
if (notificationBox.allNotifications.length === 0) {
deferred.resolve();
resolve();
}
});
notification.close();
}
return deferred.promise;
});
}
function whenDelayedStartupFinished(aWindow, aCallback) {
@ -123,9 +123,9 @@ function waitForCondition(condition, nextTest, errorMsg, retryTimes) {
}
function promiseWaitForCondition(aConditionFn) {
let deferred = Promise.defer();
waitForCondition(aConditionFn, deferred.resolve, "Condition didn't pass.");
return deferred.promise;
return new Promise(resolve => {
waitForCondition(aConditionFn, resolve, "Condition didn't pass.");
});
}
function promiseWaitForEvent(object, eventName, capturing = false, chrome = false) {
@ -185,9 +185,9 @@ function setTestPluginEnabledState(newEnabledState, pluginName) {
}
function pushPrefs(...aPrefs) {
let deferred = Promise.defer();
SpecialPowers.pushPrefEnv({"set": aPrefs}, deferred.resolve);
return deferred.promise;
return new Promise(resolve => {
SpecialPowers.pushPrefEnv({"set": aPrefs}, resolve);
});
}
function updateBlocklist(aCallback) {
@ -238,7 +238,7 @@ function promiseWindowClosed(win) {
}
function promiseOpenAndLoadWindow(aOptions, aWaitForDelayedStartup = false) {
let deferred = Promise.defer();
return new Promise(resolve => {
let win = OpenBrowserWindow(aOptions);
if (aWaitForDelayedStartup) {
Services.obs.addObserver(function onDS(aSubject, aTopic, aData) {
@ -246,15 +246,15 @@ function promiseOpenAndLoadWindow(aOptions, aWaitForDelayedStartup = false) {
return;
}
Services.obs.removeObserver(onDS, "browser-delayed-startup-finished");
deferred.resolve(win);
resolve(win);
}, "browser-delayed-startup-finished");
} else {
win.addEventListener("load", function() {
deferred.resolve(win);
resolve(win);
}, {once: true});
}
return deferred.promise;
});
}
/**
@ -304,12 +304,12 @@ function waitForAsyncUpdates(aCallback, aScope, aArguments) {
* @rejects JavaScript exception.
*/
function promiseIsURIVisited(aURI, aExpectedValue) {
let deferred = Promise.defer();
return new Promise(resolve => {
PlacesUtils.asyncHistory.isURIVisited(aURI, function(unused, aIsVisited) {
deferred.resolve(aIsVisited);
resolve(aIsVisited);
});
return deferred.promise;
});
}
function whenNewTabLoaded(aWindow, aCallback) {
@ -329,9 +329,9 @@ function whenTabLoaded(aTab, aCallback) {
}
function promiseTabLoaded(aTab) {
let deferred = Promise.defer();
whenTabLoaded(aTab, deferred.resolve);
return deferred.promise;
return new Promise(resolve => {
whenTabLoaded(aTab, resolve);
});
}
/**
@ -343,12 +343,12 @@ function promiseTabLoaded(aTab) {
* True if each visit to the URI should be cleared, false otherwise
*/
function promiseHistoryClearedState(aURIs, aShouldBeCleared) {
let deferred = Promise.defer();
return new Promise(resolve => {
let callbackCount = 0;
let niceStr = aShouldBeCleared ? "no longer" : "still";
function callbackDone() {
if (++callbackCount == aURIs.length)
deferred.resolve();
resolve();
}
aURIs.forEach(function(aURI) {
PlacesUtils.asyncHistory.isURIVisited(aURI, function(uri, isVisited) {
@ -358,7 +358,7 @@ function promiseHistoryClearedState(aURIs, aShouldBeCleared) {
});
});
return deferred.promise;
});
}
/**
@ -676,12 +676,12 @@ function promisePopupEvent(popup, eventSuffix) {
return Promise.resolve();
let eventType = "popup" + eventSuffix;
let deferred = Promise.defer();
return new Promise(resolve => {
popup.addEventListener(eventType, function(event) {
deferred.resolve();
resolve();
}, {once: true});
return deferred.promise;
});
}
function promisePopupShown(popup) {

View File

@ -16,13 +16,13 @@ XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils",
* @rejects Never.
*/
function promiseTopicObserved(topic) {
let deferred = Promise.defer();
return new Promise(resolve => {
info("Waiting for observer topic " + topic);
Services.obs.addObserver(function PTO_observe(obsSubject, obsTopic, obsData) {
Services.obs.removeObserver(PTO_observe, obsTopic);
deferred.resolve([obsSubject, obsData]);
resolve([obsSubject, obsData]);
}, topic);
return deferred.promise;
});
}
/**

View File

@ -409,12 +409,12 @@ function test() {
function promiseOneMessage(tab, messageName) {
let mm = tab.linkedBrowser.messageManager;
let deferred = Promise.defer();
return new Promise(resolve => {
mm.addMessageListener(messageName, function onmessage(message) {
mm.removeMessageListener(messageName, onmessage);
deferred.resolve(message);
resolve(message);
});
});
return deferred.promise;
}
function promiseNewTabLoadEvent(aUrl) {
@ -432,7 +432,7 @@ function promiseNewTabLoadEvent(aUrl) {
// Returns a promise which is resolved with the iframe's URL after a new
// tab is created and the iframe in that tab loads.
function promiseNewTabWithIframeLoadEvent(aUrl) {
let deferred = Promise.defer();
return new Promise(resolve => {
let tab = gBrowser.selectedTab = gBrowser.addTab(aUrl);
let browser = tab.linkedBrowser;
let mm = browser.messageManager;
@ -441,25 +441,25 @@ function promiseNewTabWithIframeLoadEvent(aUrl) {
// and wait for it to tell us about the iframe load.
mm.addMessageListener("test:iframe:load", function onFrameLoad(message) {
mm.removeMessageListener("test:iframe:load", onFrameLoad);
deferred.resolve([tab, message.data.url]);
resolve([tab, message.data.url]);
});
mm.loadFrameScript(CHROME_BASE + "content_aboutAccounts.js", true);
return deferred.promise;
});
}
function checkVisibilities(tab, data) {
let ids = Object.keys(data);
let mm = tab.linkedBrowser.messageManager;
let deferred = Promise.defer();
return new Promise(resolve => {
mm.addMessageListener("test:check-visibilities-response", function onResponse(message) {
mm.removeMessageListener("test:check-visibilities-response", onResponse);
for (let id of ids) {
is(message.data[id], data[id], "Element '" + id + "' has correct visibility");
}
deferred.resolve();
resolve();
});
mm.sendAsyncMessage("test:check-visibilities", {ids});
return deferred.promise;
});
}
// watch out - these will fire observers which if you aren't careful, may

View File

@ -9,7 +9,7 @@ registerCleanupFunction(function() {
});
function promiseNotification(aBrowser, value, expected, input) {
let deferred = Promise.defer();
return new Promise(resolve => {
let notificationBox = aBrowser.getNotificationBox(aBrowser.selectedBrowser);
if (expected) {
info("Waiting for " + value + " notification");
@ -18,7 +18,7 @@ function promiseNotification(aBrowser, value, expected, input) {
info("Saw the notification");
notificationObserver.disconnect();
notificationObserver = null;
deferred.resolve();
resolve();
}
}
if (notificationObserver) {
@ -30,10 +30,10 @@ function promiseNotification(aBrowser, value, expected, input) {
setTimeout(() => {
is(notificationBox.getNotificationWithValue(value), null,
`We are expecting to not get a notification for ${input}`);
deferred.resolve();
resolve();
}, 1000);
}
return deferred.promise;
});
}
async function runURLBarSearchTest({valueToOpen, expectSearch, expectNotification, aWindow = window}) {
@ -131,9 +131,9 @@ function get_test_function_for_localhost_with_hostname(hostName, isPrivate) {
let promiseWin = BrowserTestUtils.waitForNewWindow();
win = OpenBrowserWindow({private: true});
await promiseWin;
let deferredOpenFocus = Promise.defer();
waitForFocus(deferredOpenFocus.resolve, win);
await deferredOpenFocus.promise;
await new Promise(resolve => {
waitForFocus(resolve, win);
});
} else {
win = window;
}
@ -174,10 +174,10 @@ function get_test_function_for_localhost_with_hostname(hostName, isPrivate) {
if (isPrivate) {
info("Waiting for private window to close");
await BrowserTestUtils.closeWindow(win);
let deferredFocus = Promise.defer();
await new Promise(resolve => {
info("Waiting for focus");
waitForFocus(deferredFocus.resolve, window);
await deferredFocus.promise;
waitForFocus(resolve, window);
});
}
}
}

View File

@ -138,12 +138,12 @@ function promisePopupEvent(popup, eventSuffix) {
return Promise.resolve();
let eventType = "popup" + eventSuffix;
let deferred = Promise.defer();
return new Promise(resolve => {
popup.addEventListener(eventType, function(event) {
deferred.resolve();
resolve();
}, {once: true});
return deferred.promise;
});
}
function promisePopupShown(popup) {

View File

@ -31,9 +31,9 @@ function waitForCondition(condition, nextTest, errorMsg, retryTimes) {
}
function promiseWaitForCondition(aConditionFn, retryTimes) {
let deferred = Promise.defer();
waitForCondition(aConditionFn, deferred.resolve, "Condition didn't pass.", retryTimes);
return deferred.promise;
return new Promise(resolve => {
waitForCondition(aConditionFn, resolve, "Condition didn't pass.", retryTimes);
});
}
/**
@ -137,15 +137,15 @@ async function assertWebRTCIndicatorStatus(expected) {
if (document.readyState != "complete") {
info("Waiting for the sharing indicator's document to load");
let deferred = Promise.defer();
await new Promise(resolve => {
document.addEventListener("readystatechange",
function onReadyStateChange() {
if (document.readyState != "complete")
return;
document.removeEventListener("readystatechange", onReadyStateChange);
deferred.resolve();
resolve();
});
});
await deferred.promise;
}
for (let item of ["video", "audio", "screen"]) {
@ -166,12 +166,12 @@ function promisePopupEvent(popup, eventSuffix) {
return Promise.resolve();
let eventType = "popup" + eventSuffix;
let deferred = Promise.defer();
return new Promise(resolve => {
popup.addEventListener(eventType, function(event) {
deferred.resolve();
resolve();
}, {once: true});
return deferred.promise;
});
}
function promiseNotificationShown(notification) {
@ -274,47 +274,47 @@ function promiseMessage(aMessage, aAction) {
}
function promisePopupNotificationShown(aName, aAction) {
let deferred = Promise.defer();
return new Promise(resolve => {
PopupNotifications.panel.addEventListener("popupshown", function() {
ok(!!PopupNotifications.getNotification(aName), aName + " notification shown");
ok(PopupNotifications.isPanelOpen, "notification panel open");
ok(!!PopupNotifications.panel.firstChild, "notification panel populated");
deferred.resolve();
resolve();
}, {once: true});
if (aAction)
aAction();
return deferred.promise;
});
}
function promisePopupNotification(aName) {
let deferred = Promise.defer();
return new Promise(resolve => {
waitForCondition(() => PopupNotifications.getNotification(aName),
() => {
ok(!!PopupNotifications.getNotification(aName),
aName + " notification appeared");
deferred.resolve();
resolve();
}, "timeout waiting for popup notification " + aName);
return deferred.promise;
});
}
function promiseNoPopupNotification(aName) {
let deferred = Promise.defer();
return new Promise(resolve => {
waitForCondition(() => !PopupNotifications.getNotification(aName),
() => {
ok(!PopupNotifications.getNotification(aName),
aName + " notification removed");
deferred.resolve();
resolve();
}, "timeout waiting for popup notification " + aName + " to disappear");
return deferred.promise;
});
}
const kActionAlways = 1;

View File

@ -28,20 +28,20 @@ add_task(async function() {
});
function promiseFullscreenChange() {
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
info("Wait for fullscreen change");
let timeoutId = setTimeout(() => {
window.removeEventListener("fullscreen", onFullscreenChange, true);
deferred.reject("Fullscreen change did not happen within " + 20000 + "ms");
reject("Fullscreen change did not happen within " + 20000 + "ms");
}, 20000);
function onFullscreenChange(event) {
clearTimeout(timeoutId);
window.removeEventListener("fullscreen", onFullscreenChange, true);
info("Fullscreen event received");
deferred.resolve();
resolve();
}
window.addEventListener("fullscreen", onFullscreenChange, true);
return deferred.promise;
});
}

View File

@ -33,19 +33,19 @@ add_task(function asyncCleanup() {
});
function waitForPageLoad(aTab) {
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
let timeoutId = setTimeout(() => {
aTab.linkedBrowser.removeEventListener("load", onTabLoad, true);
deferred.reject("Page didn't load within " + 20000 + "ms");
reject("Page didn't load within " + 20000 + "ms");
}, 20000);
function onTabLoad(event) {
clearTimeout(timeoutId);
aTab.linkedBrowser.removeEventListener("load", onTabLoad, true);
info("Tab event received: load");
deferred.resolve();
resolve();
}
aTab.linkedBrowser.addEventListener("load", onTabLoad, true, true);
return deferred.promise;
});
}

View File

@ -59,32 +59,32 @@ add_task(async function() {
});
function promiseObserverNotification(aObserver) {
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
function notificationCallback(e) {
Services.obs.removeObserver(notificationCallback, aObserver);
clearTimeout(timeoutId);
deferred.resolve();
resolve();
}
let timeoutId = setTimeout(() => {
Services.obs.removeObserver(notificationCallback, aObserver);
deferred.reject("Notification '" + aObserver + "' did not happen within 20 seconds.");
reject("Notification '" + aObserver + "' did not happen within 20 seconds.");
}, kTimeoutInMS);
Services.obs.addObserver(notificationCallback, aObserver);
return deferred.promise;
});
}
function promiseTabSelect() {
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
let container = window.gBrowser.tabContainer;
let timeoutId = setTimeout(() => {
container.removeEventListener("TabSelect", callback);
deferred.reject("TabSelect did not happen within 20 seconds");
reject("TabSelect did not happen within 20 seconds");
}, kTimeoutInMS);
function callback(e) {
container.removeEventListener("TabSelect", callback);
clearTimeout(timeoutId);
executeSoon(deferred.resolve);
executeSoon(resolve);
}
container.addEventListener("TabSelect", callback);
return deferred.promise;
});
}

View File

@ -17,16 +17,16 @@ const kSmallWidth = 400;
* resolves as soon as the menu is ready for interaction.
*/
function bookmarksMenuPanelShown() {
let deferred = Promise.defer();
return new Promise(resolve => {
let bookmarksMenuPopup = document.getElementById("BMB_bookmarksPopup");
let onTransitionEnd = (e) => {
if (e.target == bookmarksMenuPopup) {
bookmarksMenuPopup.removeEventListener("transitionend", onTransitionEnd);
deferred.resolve();
resolve();
}
}
bookmarksMenuPopup.addEventListener("transitionend", onTransitionEnd);
return deferred.promise;
});
}
/**

View File

@ -97,7 +97,7 @@ add_task(async function() {
// reusing it prevents a potential race between unload handlers where the
// one from promiseWindowClosed could fire before the onWindowClosed
// (and therefore onAreaNodeRegistered) one, causing the test to fail.
let windowCloseDeferred = Promise.defer();
let windowClosed = await new Promise(resolve => {
listener = {
onAreaNodeUnregistered(aArea, aNode, aReason) {
if (aArea == TOOLBARID) {
@ -108,7 +108,7 @@ add_task(async function() {
},
onWindowClosed(aWindow) {
if (aWindow == otherWin) {
windowCloseDeferred.resolve(aWindow);
resolve(aWindow);
} else {
info("Other window was closed!");
info("Other window title: " + (aWindow.document && aWindow.document.title));
@ -118,7 +118,7 @@ add_task(async function() {
};
CustomizableUI.addListener(listener);
otherWin.close();
let windowClosed = await windowCloseDeferred.promise;
});
is(windowClosed, otherWin, "Window should have sent onWindowClosed notification.");
ok(wasInformedCorrectlyOfAreaDisappearing, "Should be told about window closing.");

View File

@ -88,7 +88,7 @@ async function openPrefsFromMenuPanel(expectedPanelId, entryPoint) {
let setupButton = subpanel.querySelector(".PanelUI-remotetabs-prefs-button");
setupButton.click();
let deferred = Promise.defer();
await new Promise(resolve => {
let handler = (e) => {
if (e.originalTarget != gBrowser.selectedBrowser.contentDocument ||
e.target.location.href == "about:blank") {
@ -96,11 +96,11 @@ async function openPrefsFromMenuPanel(expectedPanelId, entryPoint) {
return;
}
gBrowser.selectedBrowser.removeEventListener("load", handler, true);
deferred.resolve();
resolve();
}
gBrowser.selectedBrowser.addEventListener("load", handler, true);
await deferred.promise;
});
newTab = gBrowser.selectedTab;
is(gBrowser.currentURI.spec, "about:preferences?entrypoint=" + entryPoint + "#sync",

View File

@ -203,16 +203,16 @@ function endCustomizing(aWindow = window) {
return true;
}
Services.prefs.setBoolPref("browser.uiCustomization.disableAnimation", true);
let deferredEndCustomizing = Promise.defer();
return new Promise(resolve => {
function onCustomizationEnds() {
Services.prefs.setBoolPref("browser.uiCustomization.disableAnimation", false);
aWindow.gNavToolbox.removeEventListener("aftercustomization", onCustomizationEnds);
deferredEndCustomizing.resolve();
resolve();
}
aWindow.gNavToolbox.addEventListener("aftercustomization", onCustomizationEnds);
aWindow.gCustomizeMode.exit();
return deferredEndCustomizing.promise;
});
}
function startCustomizing(aWindow = window) {
@ -220,28 +220,28 @@ function startCustomizing(aWindow = window) {
return null;
}
Services.prefs.setBoolPref("browser.uiCustomization.disableAnimation", true);
let deferred = Promise.defer();
return new Promise(resolve => {
function onCustomizing() {
aWindow.gNavToolbox.removeEventListener("customizationready", onCustomizing);
Services.prefs.setBoolPref("browser.uiCustomization.disableAnimation", false);
deferred.resolve();
resolve();
}
aWindow.gNavToolbox.addEventListener("customizationready", onCustomizing);
aWindow.gCustomizeMode.enter();
return deferred.promise;
});
}
function promiseObserverNotified(aTopic) {
let deferred = Promise.defer();
return new Promise(resolve => {
Services.obs.addObserver(function onNotification(subject, topic, data) {
Services.obs.removeObserver(onNotification, topic);
deferred.resolve({subject, data});
resolve({subject, data});
}, aTopic);
return deferred.promise;
});
}
function openAndLoadWindow(aOptions, aWaitForDelayedStartup = false) {
let deferred = Promise.defer();
return new Promise(resolve => {
let win = OpenBrowserWindow(aOptions);
if (aWaitForDelayedStartup) {
Services.obs.addObserver(function onDS(aSubject, aTopic, aData) {
@ -249,24 +249,24 @@ function openAndLoadWindow(aOptions, aWaitForDelayedStartup = false) {
return;
}
Services.obs.removeObserver(onDS, "browser-delayed-startup-finished");
deferred.resolve(win);
resolve(win);
}, "browser-delayed-startup-finished");
} else {
win.addEventListener("load", function() {
deferred.resolve(win);
resolve(win);
}, {once: true});
}
return deferred.promise;
});
}
function promiseWindowClosed(win) {
let deferred = Promise.defer();
return new Promise(resolve => {
win.addEventListener("unload", function() {
deferred.resolve();
resolve();
}, {once: true});
win.close();
return deferred.promise;
});
}
function promisePanelShown(win) {
@ -280,17 +280,17 @@ function promiseOverflowShown(win) {
}
function promisePanelElementShown(win, aPanel) {
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
let timeoutId = win.setTimeout(() => {
deferred.reject("Panel did not show within 20 seconds.");
reject("Panel did not show within 20 seconds.");
}, 20000);
function onPanelOpen(e) {
aPanel.removeEventListener("popupshown", onPanelOpen);
win.clearTimeout(timeoutId);
deferred.resolve();
resolve();
}
aPanel.addEventListener("popupshown", onPanelOpen);
return deferred.promise;
});
}
function promisePanelHidden(win) {
@ -304,17 +304,17 @@ function promiseOverflowHidden(win) {
}
function promisePanelElementHidden(win, aPanel) {
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
let timeoutId = win.setTimeout(() => {
deferred.reject("Panel did not hide within 20 seconds.");
reject("Panel did not hide within 20 seconds.");
}, 20000);
function onPanelClose(e) {
aPanel.removeEventListener("popuphidden", onPanelClose);
win.clearTimeout(timeoutId);
deferred.resolve();
resolve();
}
aPanel.addEventListener("popuphidden", onPanelClose);
return deferred.promise;
});
}
function isPanelUIOpen() {
@ -322,33 +322,33 @@ function isPanelUIOpen() {
}
function subviewShown(aSubview) {
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
let win = aSubview.ownerGlobal;
let timeoutId = win.setTimeout(() => {
deferred.reject("Subview (" + aSubview.id + ") did not show within 20 seconds.");
reject("Subview (" + aSubview.id + ") did not show within 20 seconds.");
}, 20000);
function onViewShowing(e) {
aSubview.removeEventListener("ViewShowing", onViewShowing);
win.clearTimeout(timeoutId);
deferred.resolve();
resolve();
}
aSubview.addEventListener("ViewShowing", onViewShowing);
return deferred.promise;
});
}
function subviewHidden(aSubview) {
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
let win = aSubview.ownerGlobal;
let timeoutId = win.setTimeout(() => {
deferred.reject("Subview (" + aSubview.id + ") did not hide within 20 seconds.");
reject("Subview (" + aSubview.id + ") did not hide within 20 seconds.");
}, 20000);
function onViewHiding(e) {
aSubview.removeEventListener("ViewHiding", onViewHiding);
win.clearTimeout(timeoutId);
deferred.resolve();
resolve();
}
aSubview.addEventListener("ViewHiding", onViewHiding);
return deferred.promise;
});
}
function waitForCondition(aConditionFn, aMaxTries = 50, aCheckInterval = 100) {
@ -372,9 +372,9 @@ function waitForCondition(aConditionFn, aMaxTries = 50, aCheckInterval = 100) {
}
function waitFor(aTimeout = 100) {
let deferred = Promise.defer();
setTimeout(() => deferred.resolve(), aTimeout);
return deferred.promise;
return new Promise(resolve => {
setTimeout(() => resolve(), aTimeout);
});
}
/**
@ -401,11 +401,11 @@ function promiseTabLoadEvent(aTab, aURL) {
* @return {Promise} resolved when navigation has finished.
*/
function promiseTabHistoryNavigation(aDirection = -1, aConditionFn) {
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
let timeoutId = setTimeout(() => {
gBrowser.removeEventListener("pageshow", listener, true);
deferred.reject("Pageshow did not happen within " + kTabEventFailureTimeoutInMs + "ms");
reject("Pageshow did not happen within " + kTabEventFailureTimeoutInMs + "ms");
}, kTabEventFailureTimeoutInMs);
function listener(event) {
@ -413,17 +413,17 @@ function promiseTabHistoryNavigation(aDirection = -1, aConditionFn) {
clearTimeout(timeoutId);
if (aConditionFn) {
waitForCondition(aConditionFn).then(() => deferred.resolve(),
aReason => deferred.reject(aReason));
waitForCondition(aConditionFn).then(() => resolve(),
aReason => reject(aReason));
} else {
deferred.resolve();
resolve();
}
}
gBrowser.addEventListener("pageshow", listener, true);
content.history.go(aDirection);
return deferred.promise;
});
}
/**
@ -479,16 +479,16 @@ function popupHidden(aPopup) {
* yield popupHiddenPromise;
*/
function promisePopupEvent(aPopup, aEventSuffix) {
let deferred = Promise.defer();
return new Promise(resolve => {
let eventType = "popup" + aEventSuffix;
function onPopupEvent(e) {
aPopup.removeEventListener(eventType, onPopupEvent);
deferred.resolve();
resolve();
}
aPopup.addEventListener(eventType, onPopupEvent);
return deferred.promise;
});
}
// This is a simpler version of the context menu check that

View File

@ -98,18 +98,18 @@ function unlockWidth(aItemIDs) {
* @param aIsOverflowed if we're waiting for the item to be overflowed.
*/
function waitForOverflowed(aItem, aIsOverflowed) {
let deferOverflow = Promise.defer();
return new Promise(resolve => {
if (aItem.overflowed == aIsOverflowed) {
return deferOverflow.resolve();
return resolve();
}
let observer = new MutationObserver(function(aMutations) {
if (aItem.overflowed == aIsOverflowed) {
observer.disconnect();
deferOverflow.resolve();
resolve();
}
});
observer.observe(aItem.node, {attributes: true});
return deferOverflow.promise;
});
}

View File

@ -64,7 +64,7 @@ function promiseOpenAndLoadWindow(aOptions) {
* @rejects if a valid load event is not received within a meaningful interval
*/
function promiseTabLoadEvent(tab, url, eventType = "load") {
let deferred = Promise.defer();
return new Promise(resolve => {
info("Wait tab event: " + eventType);
function handle(event) {
@ -79,7 +79,7 @@ function promiseTabLoadEvent(tab, url, eventType = "load") {
realCleanup = () => {};
tab.linkedBrowser.removeEventListener(eventType, handle, true);
info("Tab event received: " + eventType);
deferred.resolve(event);
resolve(event);
}
// Juggle a bit to avoid leaks:
@ -89,7 +89,7 @@ function promiseTabLoadEvent(tab, url, eventType = "load") {
tab.linkedBrowser.addEventListener(eventType, handle, true, true);
if (url)
tab.linkedBrowser.loadURI(url);
return deferred.promise;
});
}
function promiseWindowClosed(win) {
@ -107,16 +107,16 @@ function promiseWindowClosed(win) {
function promiseFocus() {
let deferred = Promise.defer();
waitForFocus(deferred.resolve);
return deferred.promise;
return new Promise(resolve => {
waitForFocus(resolve);
});
}
function promisePanelOpened() {
let deferred = Promise.defer();
return new Promise(resolve => {
if (DownloadsPanel.panel && DownloadsPanel.panel.state == "open") {
return deferred.resolve();
return resolve();
}
// Hook to wait until the panel is shown.
@ -127,10 +127,10 @@ function promisePanelOpened() {
// Defer to the next tick of the event loop so that we don't continue
// processing during the DOM event handler itself.
setTimeout(deferred.resolve, 0);
setTimeout(resolve, 0);
};
return deferred.promise;
});
}
async function task_resetState() {

View File

@ -151,13 +151,13 @@ function synthesizeClickOnSelectedTreeCell(aTree, aOptions) {
* @rejects JavaScript exception.
*/
function promiseIsURIVisited(aURI) {
let deferred = Promise.defer();
return new Promise(resolve => {
PlacesUtils.asyncHistory.isURIVisited(aURI, function(unused, aIsVisited) {
deferred.resolve(aIsVisited);
resolve(aIsVisited);
});
return deferred.promise;
});
}
function promiseBookmarksNotification(notification, conditionFn) {

View File

@ -24,7 +24,7 @@ add_task(async function() {
});
function openPreferencesViaHash(aPane) {
let deferred = Promise.defer();
return new Promise(resolve => {
gBrowser.selectedTab = gBrowser.addTab("about:preferences" + (aPane ? "#" + aPane : ""));
let newTabBrowser = gBrowser.selectedBrowser;
@ -33,9 +33,9 @@ function openPreferencesViaHash(aPane) {
let win = gBrowser.contentWindow;
let selectedPane = win.history.state;
gBrowser.removeCurrentTab();
deferred.resolve({selectedPane});
resolve({selectedPane});
}, {once: true});
}, {capture: true, once: true});
return deferred.promise;
});
}

View File

@ -129,7 +129,7 @@ function waitForEvent(aSubject, aEventName, aTimeoutMs, aTarget) {
}
function openPreferencesViaOpenPreferencesAPI(aPane, aAdvancedTab, aOptions) {
let deferred = Promise.defer();
return new Promise(resolve => {
gBrowser.selectedTab = gBrowser.addTab("about:blank");
openPreferences(aPane, aAdvancedTab ? {advancedTab: aAdvancedTab} : undefined);
let newTabBrowser = gBrowser.selectedBrowser;
@ -142,11 +142,11 @@ function openPreferencesViaOpenPreferencesAPI(aPane, aAdvancedTab, aOptions) {
let selectedAdvancedTab = aAdvancedTab && doc.getElementById("advancedPrefs").selectedTab.id;
if (!aOptions || !aOptions.leaveOpen)
gBrowser.removeCurrentTab();
deferred.resolve({selectedPane, selectedAdvancedTab});
resolve({selectedPane, selectedAdvancedTab});
}, {once: true});
}, {capture: true, once: true});
return deferred.promise;
});
}
function waitForCondition(aConditionFn, aMaxTries = 50, aCheckInterval = 100) {

View File

@ -60,7 +60,7 @@ add_task(async function() {
function openPreferencesViaHash(aPane) {
let deferred = Promise.defer();
return new Promise(resolve => {
gBrowser.selectedTab = gBrowser.addTab("about:preferences" + (aPane ? "#" + aPane : ""));
let newTabBrowser = gBrowser.selectedBrowser;
@ -69,9 +69,9 @@ function openPreferencesViaHash(aPane) {
let win = gBrowser.contentWindow;
let selectedPane = win.history.state;
gBrowser.removeCurrentTab();
deferred.resolve({selectedPane});
resolve({selectedPane});
}, {once: true});
}, {capture: true, once: true});
return deferred.promise;
});
}

View File

@ -120,7 +120,7 @@ function waitForEvent(aSubject, aEventName, aTimeoutMs, aTarget) {
}
function openPreferencesViaOpenPreferencesAPI(aPane, aOptions) {
let deferred = Promise.defer();
return new Promise(resolve => {
gBrowser.selectedTab = gBrowser.addTab("about:blank");
openPreferences(aPane);
let newTabBrowser = gBrowser.selectedBrowser;
@ -131,11 +131,11 @@ function openPreferencesViaOpenPreferencesAPI(aPane, aOptions) {
let selectedPane = win.history.state;
if (!aOptions || !aOptions.leaveOpen)
gBrowser.removeCurrentTab();
deferred.resolve({selectedPane});
resolve({selectedPane});
}, {once: true});
}, {capture: true, once: true});
return deferred.promise;
});
}
function waitForCondition(aConditionFn, aMaxTries = 50, aCheckInterval = 100) {

View File

@ -16,11 +16,11 @@ function checkUrlbarFocus(win) {
}
function openNewPrivateWindow() {
let deferred = Promise.defer();
return new Promise(resolve => {
whenNewWindowLoaded({private: true}, win => {
executeSoon(() => deferred.resolve(win));
executeSoon(() => resolve(win));
});
});
return deferred.promise;
}
add_task(async function() {

View File

@ -110,9 +110,9 @@ add_task(async function flush_on_tabclose_racy() {
});
function promiseNewWindow() {
let deferred = Promise.defer();
whenNewWindowLoaded({private: false}, deferred.resolve);
return deferred.promise;
return new Promise(resolve => {
whenNewWindowLoaded({private: false}, resolve);
});
}
async function createTabWithStorageData(urls, win = window) {

View File

@ -148,7 +148,7 @@ add_task(async function() {
// helper functions
function waitForLoadsInBrowser(aBrowser, aLoadCount) {
let deferred = Promise.defer();
return new Promise(resolve => {
let loadCount = 0;
aBrowser.addEventListener("load", function(aEvent) {
if (++loadCount < aLoadCount) {
@ -157,14 +157,14 @@ function waitForLoadsInBrowser(aBrowser, aLoadCount) {
}
aBrowser.removeEventListener("load", arguments.callee, true);
deferred.resolve();
resolve();
}, true);
return deferred.promise;
});
}
function timeout(delay, task) {
let deferred = Promise.defer();
setTimeout(() => deferred.resolve(true), delay);
task.then(() => deferred.resolve(false), deferred.reject);
return deferred.promise;
return new Promise((resolve, reject) => {
setTimeout(() => resolve(true), delay);
task.then(() => resolve(false), reject);
});
}

View File

@ -18,9 +18,9 @@ add_task(async function() {
});
function promiseDelayedStartupFinished(win) {
let deferred = Promise.defer();
whenDelayedStartupFinished(win, deferred.resolve);
return deferred.promise;
return new Promise(resolve => {
whenDelayedStartupFinished(win, resolve);
});
}
function promiseBrowserHasURL(browser, url) {

View File

@ -318,13 +318,13 @@ BingRequest.prototype = {
"</TranslateArrayRequest>";
// Set up request options.
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
let options = {
onLoad: (responseText, xhr) => {
deferred.resolve(this);
resolve(this);
},
onError(e, responseText, xhr) {
deferred.reject(xhr);
reject(xhr);
},
postData: requestString,
headers
@ -336,7 +336,7 @@ BingRequest.prototype = {
// Override the response MIME type.
request.overrideMimeType("text/xml");
this.networkRequest = request;
return deferred.promise;
});
})();
}
};

View File

@ -311,13 +311,13 @@ YandexRequest.prototype = {
}
// Set up request options.
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
let options = {
onLoad: (responseText, xhr) => {
deferred.resolve(this);
resolve(this);
},
onError(e, responseText, xhr) {
deferred.reject(xhr);
reject(xhr);
},
postData: params
};
@ -325,7 +325,7 @@ YandexRequest.prototype = {
// Fire the request.
this.networkRequest = httpRequest(url, options);
return deferred.promise;
});
})();
}
};

View File

@ -119,7 +119,7 @@ function constructFixtureURL(filename) {
* @param String url A URL to be loaded in the new tab.
*/
function promiseTestPageLoad(url) {
let deferred = Promise.defer();
return new Promise(resolve => {
let tab = gBrowser.selectedTab = gBrowser.addTab(url);
let browser = gBrowser.selectedBrowser;
browser.addEventListener("load", function listener() {
@ -127,7 +127,7 @@ function promiseTestPageLoad(url) {
return;
info("Page loaded: " + browser.currentURI.spec);
browser.removeEventListener("load", listener, true);
deferred.resolve(tab);
resolve(tab);
}, true);
return deferred.promise;
});
}

View File

@ -57,26 +57,26 @@ function getDomainExceptions() {
}
function getInfoBar() {
let deferred = Promise.defer();
return new Promise(resolve => {
let infobar =
gBrowser.getNotificationBox().getNotificationWithValue("translation");
if (!infobar) {
deferred.resolve();
resolve();
} else {
// Wait for all animations to finish
Promise.all(infobar.getAnimations().map(animation => animation.finished))
.then(() => deferred.resolve(infobar));
.then(() => resolve(infobar));
}
return deferred.promise;
});
}
function openPopup(aPopup) {
let deferred = Promise.defer();
return new Promise(resolve => {
aPopup.addEventListener("popupshown", function() {
deferred.resolve();
resolve();
}, {once: true});
aPopup.focus();
@ -84,17 +84,17 @@ function openPopup(aPopup) {
EventUtils.synthesizeKey("VK_DOWN",
{ altKey: !navigator.platform.includes("Mac") });
return deferred.promise;
});
}
function waitForWindowLoad(aWin) {
let deferred = Promise.defer();
return new Promise(resolve => {
aWin.addEventListener("load", function() {
deferred.resolve();
resolve();
}, {capture: true, once: true});
return deferred.promise;
});
}

View File

@ -107,7 +107,7 @@ function constructFixtureURL(filename) {
* @param String url A URL to be loaded in the new tab.
*/
function promiseTestPageLoad(url) {
let deferred = Promise.defer();
return new Promise(resolve => {
let tab = gBrowser.selectedTab = gBrowser.addTab(url);
let browser = gBrowser.selectedBrowser;
browser.addEventListener("load", function listener() {
@ -115,9 +115,9 @@ function promiseTestPageLoad(url) {
return;
info("Page loaded: " + browser.currentURI.spec);
browser.removeEventListener("load", listener, true);
deferred.resolve(tab);
resolve(tab);
}, true);
return deferred.promise;
});
}
function showTranslationUI(tab, aDetectedLanguage) {

View File

@ -60,7 +60,7 @@ add_task(async function test_windowless_UITour() {
Services.perms.add(pageURI, "uitour", Services.perms.ALLOW_ACTION);
// UITour's ping will resolve this promise.
let deferredPing = Promise.defer();
await new Promise(resolve => {
// Create a windowless browser and test that UITour works in it.
let browserPromise = createHiddenBrowser(pageURL);
@ -92,11 +92,11 @@ add_task(async function test_windowless_UITour() {
destroyHiddenBrowser(frameInfo.frame, frameInfo.browser);
// Resolve our promise.
deferredPing.resolve();
resolve();
});
}, true);
});
// Wait for the UITour ping to complete.
await deferredPing.promise;
});
});

View File

@ -12,27 +12,27 @@ const SINGLE_TRY_TIMEOUT = 100;
const NUMBER_OF_TRIES = 30;
function waitForConditionPromise(condition, timeoutMsg, tryCount = NUMBER_OF_TRIES) {
let defer = Promise.defer();
return new Promise((resolve, reject) => {
let tries = 0;
function checkCondition() {
if (tries >= tryCount) {
defer.reject(timeoutMsg);
reject(timeoutMsg);
}
var conditionPassed;
try {
conditionPassed = condition();
} catch (e) {
return defer.reject(e);
return reject(e);
}
if (conditionPassed) {
return defer.resolve();
return resolve();
}
tries++;
setTimeout(checkCondition, SINGLE_TRY_TIMEOUT);
return undefined;
}
setTimeout(checkCondition, SINGLE_TRY_TIMEOUT);
return defer.promise;
});
}
function waitForCondition(condition, nextTestFn, errorMsg) {

View File

@ -174,7 +174,7 @@ function installedExperimentAddons() {
// addons are uninstalled.
function uninstallAddons(addons) {
let ids = new Set(addons.map(addon => addon.id));
let deferred = Promise.defer();
return new Promise(resolve => {
let listener = {};
listener.onUninstalled = addon => {
@ -185,7 +185,7 @@ function uninstallAddons(addons) {
ids.delete(addon.id);
if (ids.size == 0) {
AddonManager.removeAddonListener(listener);
deferred.resolve();
resolve();
}
};
@ -199,7 +199,7 @@ function uninstallAddons(addons) {
addon.uninstall();
}
return deferred.promise;
});
}
/**
@ -934,12 +934,12 @@ Experiments.Experiments.prototype = {
let xhr = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);
this._networkRequest = xhr;
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
let log = this._log;
let errorhandler = (evt) => {
log.error("httpGetRequest::onError() - Error making request to " + url + ": " + evt.type);
deferred.reject(new Error("Experiments - XHR error for " + url + " - " + evt.type));
reject(new Error("Experiments - XHR error for " + url + " - " + evt.type));
this._networkRequest = null;
};
xhr.onerror = errorhandler;
@ -949,12 +949,12 @@ Experiments.Experiments.prototype = {
xhr.onload = (event) => {
if (xhr.status !== 200 && xhr.state !== 0) {
log.error("httpGetRequest::onLoad() - Request to " + url + " returned status " + xhr.status);
deferred.reject(new Error("Experiments - XHR status for " + url + " is " + xhr.status));
reject(new Error("Experiments - XHR status for " + url + " is " + xhr.status));
this._networkRequest = null;
return;
}
deferred.resolve(xhr.responseText);
resolve(xhr.responseText);
this._networkRequest = null;
};
@ -971,7 +971,7 @@ Experiments.Experiments.prototype = {
this._log.error("httpGetRequest() - Error opening request to " + url + ": " + e);
return Promise.reject(new Error("Experiments - Error opening XHR for " + url));
}
return deferred.promise;
});
},
/*
@ -1968,7 +1968,7 @@ Experiments.ExperimentEntry.prototype = {
throw new Error("Experiment addon requires a restart: " + addon.id);
}
let deferred = Promise.defer();
await new Promise((resolve, reject) => {
// Else we need to enable it.
let listener = {
@ -1978,7 +1978,7 @@ Experiments.ExperimentEntry.prototype = {
}
AddonManager.removeAddonListener(listener);
deferred.resolve();
resolve();
},
};
@ -1989,14 +1989,14 @@ Experiments.ExperimentEntry.prototype = {
}
AddonManager.removeAddonListener(listener);
deferred.reject("Failed to enable addon " + addon.id + " due to: " + handler);
reject("Failed to enable addon " + addon.id + " due to: " + handler);
};
}
this._log.info("reconcileAddonState() - Activating add-on: " + addon.id);
AddonManager.addAddonListener(listener);
addon.userDisabled = false;
await deferred.promise;
});
changes |= this.ADDON_CHANGE_ENABLE;
this._log.info("reconcileAddonState() - Add-on has been enabled: " + addon.id);
@ -2049,13 +2049,13 @@ Experiments.ExperimentEntry.prototype = {
throw new Error("shouldStop must not be called on disabled experiments.");
}
let deferred = Promise.defer();
return new Promise(resolve => {
this.isApplicable().then(
() => deferred.resolve({shouldStop: false}),
reason => deferred.resolve({shouldStop: true, reason})
() => resolve({shouldStop: false}),
reason => resolve({shouldStop: true, reason})
);
return deferred.promise;
});
},
/*

View File

@ -159,17 +159,17 @@ function startAddonManagerOnly() {
}
function getExperimentAddons(previous = false) {
let deferred = Promise.defer();
return new Promise(resolve => {
AddonManager.getAddonsByTypes(["experiment"], (addons) => {
if (previous) {
deferred.resolve(addons);
resolve(addons);
} else {
deferred.resolve(addons.filter(a => !a.appDisabled));
resolve(addons.filter(a => !a.appDisabled));
}
});
return deferred.promise;
});
}
function createAppInfo(ID = "xpcshell@tests.mozilla.org", name = "XPCShell",

View File

@ -49,13 +49,13 @@ add_task(async function test_setup() {
});
function isApplicable(experiment) {
let deferred = Promise.defer();
return new Promise(resolve => {
experiment.isApplicable().then(
result => deferred.resolve({ applicable: true, reason: null }),
reason => deferred.resolve({ applicable: false, reason })
result => resolve({ applicable: true, reason: null }),
reason => resolve({ applicable: false, reason })
);
return deferred.promise;
});
}
add_task(async function test_startStop() {

View File

@ -518,16 +518,16 @@ this.ContentSearch = {
if (!uri) {
return Promise.resolve(null);
}
let deferred = Promise.defer();
return new Promise(resolve => {
let xhr = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].
createInstance(Ci.nsIXMLHttpRequest);
xhr.open("GET", uri, true);
xhr.responseType = "arraybuffer";
xhr.onload = () => {
deferred.resolve(xhr.response);
resolve(xhr.response);
};
xhr.onerror = xhr.onabort = xhr.ontimeout = () => {
deferred.resolve(null);
resolve(null);
};
try {
// This throws if the URI is erroneously encoded.
@ -535,7 +535,7 @@ this.ContentSearch = {
} catch (err) {
return Promise.resolve(null);
}
return deferred.promise;
});
},
_ensureDataHasProperties(data, requiredProperties) {

View File

@ -153,7 +153,7 @@ var DirectoryLinksProvider = {
* @return promise resolved to json string, "{}" returned if status != 200
*/
_downloadJsonData: function DirectoryLinksProvider__downloadJsonData(uri) {
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
let xmlHttp = this._newXHR();
xmlHttp.onload = function(aResponse) {
@ -161,11 +161,11 @@ var DirectoryLinksProvider = {
if (this.status && this.status != 200) {
json = "{}";
}
deferred.resolve(json);
resolve(json);
};
xmlHttp.onerror = function(e) {
deferred.reject("Fetching " + uri + " results in error code: " + e.target.status);
reject("Fetching " + uri + " results in error code: " + e.target.status);
};
try {
@ -176,10 +176,10 @@ var DirectoryLinksProvider = {
xmlHttp.setRequestHeader("Content-Type", DIRECTORY_LINKS_TYPE);
xmlHttp.send();
} catch (e) {
deferred.reject("Error fetching " + uri);
reject("Error fetching " + uri);
Cu.reportError(e);
}
return deferred.promise;
});
},
/**

View File

@ -300,16 +300,16 @@ function checkMsg(actualMsg, expectedMsgData) {
}
function waitForMsg(name, type) {
let deferred = Promise.defer();
return new Promise(resolve => {
info("Waiting for " + name + " message " + type + "...");
gMsgMan.addMessageListener(name, function onMsg(msg) {
info("Received " + name + " message " + msg.data.type + "\n");
if (msg.data.type == type) {
gMsgMan.removeMessageListener(name, onMsg);
deferred.resolve(msg);
resolve(msg);
}
});
return deferred.promise;
});
}
function waitForTestMsg(type) {
@ -346,7 +346,7 @@ function waitForNewEngine(basename, numImages) {
}
function addTab() {
let deferred = Promise.defer();
return new Promise(resolve => {
let tab = gBrowser.addTab();
gBrowser.selectedTab = tab;
tab.linkedBrowser.addEventListener("load", function() {
@ -358,11 +358,11 @@ function addTab() {
});
waitForMsg(CONTENT_SEARCH_MSG, "AddToWhitelistAck").then(() => {
gMsgMan.loadFrameScript(url, false);
deferred.resolve();
resolve();
});
}, {capture: true, once: true});
registerCleanupFunction(() => gBrowser.removeTab(tab));
return deferred.promise;
});
}
var currentStateObj = async function() {
@ -396,21 +396,21 @@ function arrayBufferFromDataURI(uri) {
if (!uri) {
return Promise.resolve(null);
}
let deferred = Promise.defer();
return new Promise(resolve => {
let xhr = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].
createInstance(Ci.nsIXMLHttpRequest);
xhr.open("GET", uri, true);
xhr.responseType = "arraybuffer";
xhr.onerror = () => {
deferred.resolve(null);
resolve(null);
};
xhr.onload = () => {
deferred.resolve(xhr.response);
resolve(xhr.response);
};
try {
xhr.send();
} catch (err) {
return Promise.resolve(null);
}
return deferred.promise;
});
}

View File

@ -7,27 +7,27 @@ const SINGLE_TRY_TIMEOUT = 100;
const NUMBER_OF_TRIES = 30;
function waitForConditionPromise(condition, timeoutMsg, tryCount = NUMBER_OF_TRIES) {
let defer = Promise.defer();
return new Promise((resolve, reject) => {
let tries = 0;
function checkCondition() {
if (tries >= tryCount) {
defer.reject(timeoutMsg);
reject(timeoutMsg);
}
var conditionPassed;
try {
conditionPassed = condition();
} catch (e) {
return defer.reject(e);
return reject(e);
}
if (conditionPassed) {
return defer.resolve();
return resolve();
}
tries++;
setTimeout(checkCondition, SINGLE_TRY_TIMEOUT);
return undefined;
}
setTimeout(checkCondition, SINGLE_TRY_TIMEOUT);
return defer.promise;
});
}
function waitForCondition(condition, nextTest, errorMsg) {

View File

@ -90,12 +90,12 @@ function isIdentical(actual, expected) {
}
function fetchData() {
let deferred = Promise.defer();
return new Promise(resolve => {
DirectoryLinksProvider.getLinks(linkData => {
deferred.resolve(linkData);
resolve(linkData);
});
});
return deferred.promise;
}
function readJsonFile(jsonFile = DIRECTORY_LINKS_FILE) {

View File

@ -142,13 +142,13 @@ function longRunningAsyncTask(resolution = undefined, outResult = {}) {
if (!("countFinished" in outResult)) {
outResult.countFinished = 0;
}
let deferred = Promise.defer();
return new Promise(resolve => {
do_timeout(100, function() {
++outResult.countFinished;
outResult.isFinished = true;
deferred.resolve(resolution);
resolve(resolution);
});
});
return deferred.promise;
}
function get_exn(f) {

View File

@ -20,7 +20,7 @@ add_task(async function test_userContextId() {
});
function doSearch(aString, aUserContextId) {
let deferred = Promise.defer();
return new Promise(resolve => {
let search = new AutoCompleteSearch("test");
search.startSearch = function(aSearchString,
@ -28,7 +28,7 @@ function doSearch(aString, aUserContextId) {
aPreviousResult,
aListener) {
unregisterAutoCompleteSearch(search);
deferred.resolve(aSearchParam);
resolve(aSearchParam);
};
registerAutoCompleteSearch(search);
@ -40,6 +40,6 @@ function doSearch(aString, aUserContextId) {
controller.input = input;
controller.startSearch(aString);
return deferred.promise;
});
}

View File

@ -40,13 +40,13 @@ this.configureLogging = function() {
};
this.sleep = function(wait) {
let deferred = Promise.defer();
return new Promise(resolve => {
setTimeout(() => {
deferred.resolve();
resolve();
}, wait);
return deferred.promise;
});
};
this.TestingCrashManager = function(options) {

View File

@ -164,7 +164,7 @@ function processUpdateRequest() {
// Set up the local whitelist.
function waitForUpdates() {
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
gHttpServer.registerPathHandler("/downloads", function(request, response) {
let blob = processUpdateRequest();
response.setHeader("Content-Type",
@ -187,12 +187,12 @@ function waitForUpdates() {
// passed back in the callback in nsIUrlClassifierStreamUpdater on success.
do_check_eq("1000", aEvent);
do_print("All data processed");
deferred.resolve(true);
resolve(true);
}
// Just throw if we ever get an update or download error.
function handleError(aEvent) {
do_throw("We didn't download or update correctly: " + aEvent);
deferred.reject();
reject();
}
streamUpdater.downloadUpdates(
"goog-downloadwhite-digest256",
@ -200,18 +200,18 @@ function waitForUpdates() {
true,
"http://localhost:4444/downloads",
updateSuccess, handleError, handleError);
return deferred.promise;
});
}
function promiseQueryReputation(query, expectedShouldBlock) {
let deferred = Promise.defer();
return new Promise(resolve => {
function onComplete(aShouldBlock, aStatus) {
do_check_eq(Cr.NS_OK, aStatus);
do_check_eq(aShouldBlock, expectedShouldBlock);
deferred.resolve(true);
resolve(true);
}
gAppRep.queryReputation(query, onComplete);
return deferred.promise;
});
}
add_task(async function() {
@ -263,16 +263,16 @@ add_task(async function test_disabled() {
let query = {sourceURI: createURI("http://example.com"),
suggestedFileName: "noop.bat",
fileSize: 12};
let deferred = Promise.defer();
await new Promise(resolve => {
gAppRep.queryReputation(query,
function onComplete(aShouldBlock, aStatus) {
// We should be getting NS_ERROR_NOT_AVAILABLE if the service is disabled
do_check_eq(Cr.NS_ERROR_NOT_AVAILABLE, aStatus);
do_check_false(aShouldBlock);
deferred.resolve(true);
resolve(true);
}
);
await deferred.promise;
});
});
add_task(async function test_disabled_through_lists() {
@ -284,16 +284,16 @@ add_task(async function test_disabled_through_lists() {
let query = {sourceURI: createURI("http://example.com"),
suggestedFileName: "noop.bat",
fileSize: 12};
let deferred = Promise.defer();
await new Promise(resolve => {
gAppRep.queryReputation(query,
function onComplete(aShouldBlock, aStatus) {
// We should be getting NS_ERROR_NOT_AVAILABLE if the service is disabled
do_check_eq(Cr.NS_ERROR_NOT_AVAILABLE, aStatus);
do_check_false(aShouldBlock);
deferred.resolve(true);
resolve(true);
}
);
await deferred.promise;
});
});
add_task(async function test_teardown() {
gStillRunning = false;

View File

@ -75,7 +75,7 @@ function readFileToString(aFilename) {
* @rejects With an exception, if onSaveComplete is called with a failure code.
*/
function promiseSaverComplete(aSaver, aOnTargetChangeFn) {
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
aSaver.observer = {
onTargetChange: function BFSO_onSaveComplete(unused, aTarget) {
if (aOnTargetChangeFn) {
@ -84,13 +84,13 @@ function promiseSaverComplete(aSaver, aOnTargetChangeFn) {
},
onSaveComplete: function BFSO_onSaveComplete(unused, aStatus) {
if (Components.isSuccessCode(aStatus)) {
deferred.resolve();
resolve();
} else {
deferred.reject(new Components.Exception("Saver failed.", aStatus));
reject(new Components.Exception("Saver failed.", aStatus));
}
},
};
return deferred.promise;
});
}
/**
@ -108,7 +108,7 @@ function promiseSaverComplete(aSaver, aOnTargetChangeFn) {
* @rejects With an exception, if the copy fails.
*/
function promiseCopyToSaver(aSourceString, aSaverOutputStream, aCloseWhenDone) {
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
let inputStream = new StringInputStream(aSourceString, aSourceString.length);
let copier = Cc["@mozilla.org/network/async-stream-copier;1"]
.createInstance(Ci.nsIAsyncStreamCopier);
@ -118,13 +118,13 @@ function promiseCopyToSaver(aSourceString, aSaverOutputStream, aCloseWhenDone) {
onStartRequest() { },
onStopRequest(aRequest, aContext, aStatusCode) {
if (Components.isSuccessCode(aStatusCode)) {
deferred.resolve();
resolve();
} else {
deferred.reject(new Components.Exception(aStatusCode));
reject(new Components.Exception(aStatusCode));
}
},
}, null);
return deferred.promise;
});
}
// Registers a table for which to serve update chunks.
@ -261,7 +261,7 @@ function processUpdateRequest() {
// Set up the local whitelist.
function waitForUpdates() {
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
gHttpServer.registerPathHandler("/downloads", function(request, response) {
let blob = processUpdateRequest();
response.setHeader("Content-Type",
@ -284,12 +284,12 @@ function waitForUpdates() {
// passed back in the callback in nsIUrlClassifierStreamUpdater on success.
do_check_eq("1000", aEvent);
do_print("All data processed");
deferred.resolve(true);
resolve(true);
}
// Just throw if we ever get an update or download error.
function handleError(aEvent) {
do_throw("We didn't download or update correctly: " + aEvent);
deferred.reject();
reject();
}
streamUpdater.downloadUpdates(
"goog-downloadwhite-digest256",
@ -297,18 +297,18 @@ function waitForUpdates() {
true,
"http://localhost:4444/downloads",
updateSuccess, handleError, handleError);
return deferred.promise;
});
}
function promiseQueryReputation(query, expectedShouldBlock) {
let deferred = Promise.defer();
return new Promise(resolve => {
function onComplete(aShouldBlock, aStatus) {
do_check_eq(Cr.NS_OK, aStatus);
do_check_eq(aShouldBlock, expectedShouldBlock);
deferred.resolve(true);
resolve(true);
}
gAppRep.queryReputation(query, onComplete);
return deferred.promise;
});
}
add_task(async function() {
@ -390,16 +390,16 @@ add_task(async function test_disabled() {
let query = {sourceURI: createURI("http://example.com"),
suggestedFileName: "noop.bat",
fileSize: 12};
let deferred = Promise.defer();
await new Promise(resolve => {
gAppRep.queryReputation(query,
function onComplete(aShouldBlock, aStatus) {
// We should be getting NS_ERROR_NOT_AVAILABLE if the service is disabled
do_check_eq(Cr.NS_ERROR_NOT_AVAILABLE, aStatus);
do_check_false(aShouldBlock);
deferred.resolve(true);
resolve(true);
}
);
await deferred.promise;
});
});
add_task(async function test_disabled_through_lists() {
@ -411,16 +411,16 @@ add_task(async function test_disabled_through_lists() {
let query = {sourceURI: createURI("http://example.com"),
suggestedFileName: "noop.bat",
fileSize: 12};
let deferred = Promise.defer();
await new Promise(resolve => {
gAppRep.queryReputation(query,
function onComplete(aShouldBlock, aStatus) {
// We should be getting NS_ERROR_NOT_AVAILABLE if the service is disabled
do_check_eq(Cr.NS_ERROR_NOT_AVAILABLE, aStatus);
do_check_false(aShouldBlock);
deferred.resolve(true);
resolve(true);
}
);
await deferred.promise;
});
});
add_task(async function test_teardown() {
gStillRunning = false;

View File

@ -21,12 +21,12 @@ add_task(async function test_watching_non_existing() {
// Instantiate the native watcher.
let watcher = makeWatcher();
let deferred = Promise.defer();
let error = await new Promise((resolve, reject) => {
// Try watch a path which doesn't exist.
watcher.addPath(notExistingDir, deferred.reject, deferred.resolve);
watcher.addPath(notExistingDir, reject, resolve);
// Wait until the watcher informs us that there was an error.
let error = await deferred.promise;
});
do_check_eq(error, Components.results.NS_ERROR_FILE_NOT_FOUND);
});

View File

@ -492,7 +492,7 @@ this.DownloadIntegration = {
verdict: "",
});
}
let deferred = Promise.defer();
return new Promise(resolve => {
let aReferrer = null;
if (aDownload.source.referrer) {
aReferrer = NetUtil.newURI(aDownload.source.referrer);
@ -506,12 +506,12 @@ this.DownloadIntegration = {
signatureInfo: sigInfo,
redirects: channelRedirects },
function onComplete(aShouldBlock, aRv, aVerdict) {
deferred.resolve({
resolve({
shouldBlock: aShouldBlock,
verdict: (aShouldBlock && kVerdictMap[aVerdict]) || "",
});
});
return deferred.promise;
});
},
#ifdef XP_WIN

View File

@ -1635,11 +1635,11 @@ add_task(async function test_cancel_midway_restart_with_content_encoding() {
let download = await promiseStartDownload(httpUrl("interruptible_gzip.txt"));
// The first time, cancel the download midway.
let deferCancel = Promise.defer();
await new Promise(resolve => {
let onchange = function() {
if (!download.stopped && !download.canceled &&
download.currentBytes == TEST_DATA_SHORT_GZIP_ENCODED_FIRST.length) {
deferCancel.resolve(download.cancel());
resolve(download.cancel());
}
};
@ -1648,7 +1648,7 @@ add_task(async function test_cancel_midway_restart_with_content_encoding() {
download.onchange = onchange;
onchange();
await deferCancel.promise;
});
do_check_true(download.stopped);

View File

@ -161,9 +161,9 @@ function getTempFile(aLeafName) {
* @rejects Never.
*/
function promiseExecuteSoon() {
let deferred = Promise.defer();
do_execute_soon(deferred.resolve);
return deferred.promise;
return new Promise(resolve => {
do_execute_soon(resolve);
});
}
/**
@ -174,9 +174,9 @@ function promiseExecuteSoon() {
* @rejects Never.
*/
function promiseTimeout(aTime) {
let deferred = Promise.defer();
do_timeout(aTime, deferred.resolve);
return deferred.promise;
return new Promise(resolve => {
do_timeout(aTime, resolve);
});
}
/**
@ -190,7 +190,7 @@ function promiseTimeout(aTime) {
* @rejects Never.
*/
function promiseWaitForVisit(aUrl) {
let deferred = Promise.defer();
return new Promise(resolve => {
let uri = NetUtil.newURI(aUrl);
@ -202,7 +202,7 @@ function promiseWaitForVisit(aUrl) {
aTransitionType, aGUID, aHidden) {
if (aURI.equals(uri)) {
PlacesUtils.history.removeObserver(this);
deferred.resolve([aTime, aTransitionType]);
resolve([aTime, aTransitionType]);
}
},
onTitleChanged() {},
@ -212,7 +212,7 @@ function promiseWaitForVisit(aUrl) {
onDeleteVisits() {},
});
return deferred.promise;
});
}
/**
@ -226,14 +226,14 @@ function promiseWaitForVisit(aUrl) {
* @rejects JavaScript exception.
*/
function promiseIsURIVisited(aUrl) {
let deferred = Promise.defer();
return new Promise(resolve => {
PlacesUtils.asyncHistory.isURIVisited(NetUtil.newURI(aUrl),
function(aURI, aIsVisited) {
deferred.resolve(aIsVisited);
resolve(aIsVisited);
});
return deferred.promise;
});
}
/**
@ -329,7 +329,7 @@ function promiseStartLegacyDownload(aSourceUrl, aOptions) {
let transfer = Cc["@mozilla.org/transfer;1"].createInstance(Ci.nsITransfer);
let deferred = Promise.defer();
return new Promise(resolve => {
Downloads.getList(Downloads.ALL).then(function(aList) {
// Temporarily register a view that will get notified when the download we
@ -343,7 +343,7 @@ function promiseStartLegacyDownload(aSourceUrl, aOptions) {
let promise = aList.remove(aDownload);
// When the download object is ready, make it available to the caller.
promise.then(() => deferred.resolve(aDownload),
promise.then(() => resolve(aDownload),
do_report_unexpected_exception);
},
}).then(null, do_report_unexpected_exception);
@ -361,7 +361,7 @@ function promiseStartLegacyDownload(aSourceUrl, aOptions) {
isPrivate);
}).then(null, do_report_unexpected_exception);
return deferred.promise;
});
}
/**
@ -382,7 +382,7 @@ function promiseStartExternalHelperAppServiceDownload(aSourceUrl) {
let sourceURI = NetUtil.newURI(aSourceUrl ||
httpUrl("interruptible_resumable.txt"));
let deferred = Promise.defer();
return new Promise(resolve => {
Downloads.getList(Downloads.PUBLIC).then(function(aList) {
// Temporarily register a view that will get notified when the download we
@ -396,7 +396,7 @@ function promiseStartExternalHelperAppServiceDownload(aSourceUrl) {
let promise = aList.remove(aDownload);
// When the download object is ready, make it available to the caller.
promise.then(() => deferred.resolve(aDownload),
promise.then(() => resolve(aDownload),
do_report_unexpected_exception);
},
}).then(null, do_report_unexpected_exception);
@ -429,7 +429,7 @@ function promiseStartExternalHelperAppServiceDownload(aSourceUrl) {
});
}).then(null, do_report_unexpected_exception);
return deferred.promise;
});
}
/**
@ -444,13 +444,13 @@ function promiseStartExternalHelperAppServiceDownload(aSourceUrl) {
* @rejects Never.
*/
function promiseDownloadMidway(aDownload) {
let deferred = Promise.defer();
return new Promise(resolve => {
// Wait for the download to reach half of its progress.
let onchange = function() {
if (!aDownload.stopped && !aDownload.canceled && aDownload.progress == 50) {
aDownload.onchange = null;
deferred.resolve();
resolve();
}
};
@ -459,7 +459,7 @@ function promiseDownloadMidway(aDownload) {
aDownload.onchange = onchange;
onchange();
return deferred.promise;
});
}
/**
@ -532,7 +532,7 @@ function promiseVerifyContents(aPath, aExpectedContents) {
do_throw("File is empty: " + aPath);
}
let deferred = Promise.defer();
await new Promise(resolve => {
NetUtil.asyncFetch(
{ uri: NetUtil.newURI(file), loadUsingSystemPrincipal: true },
function(aInputStream, aStatus) {
@ -548,10 +548,10 @@ function promiseVerifyContents(aPath, aExpectedContents) {
// Print the string if it is short and made of printable characters.
do_check_eq(contents, aExpectedContents);
}
deferred.resolve();
resolve();
});
await deferred.promise;
});
})();
}

View File

@ -161,7 +161,7 @@ function promiseTableCount(aConnection) {
* @rejects When there's a problem accessing the URL.
*/
function promiseEntityID(aUrl) {
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
let entityID = "";
let channel = NetUtil.newChannel({
uri: NetUtil.newURI(aUrl),
@ -178,16 +178,16 @@ function promiseEntityID(aUrl) {
onStopRequest(aRequest, aContext, aStatusCode) {
if (aStatusCode == Cr.NS_BINDING_ABORTED) {
deferred.resolve(entityID);
resolve(entityID);
} else {
deferred.reject("Unexpected status code received");
reject("Unexpected status code received");
}
},
onDataAvailable() {}
});
return deferred.promise;
});
}
/**

View File

@ -39,7 +39,7 @@ function getExpirablePRTime() {
* @rejects JavaScript exception.
*/
function promiseExpirableDownloadVisit(aSourceUrl) {
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
PlacesUtils.asyncHistory.updatePlaces(
{
uri: NetUtil.newURI(aSourceUrl || httpUrl("source.txt")),
@ -52,14 +52,14 @@ function promiseExpirableDownloadVisit(aSourceUrl) {
handleError: function handleError(aResultCode, aPlaceInfo) {
let ex = new Components.Exception("Unexpected error in adding visits.",
aResultCode);
deferred.reject(ex);
reject(ex);
},
handleResult() {},
handleCompletion: function handleCompletion() {
deferred.resolve();
resolve();
}
});
return deferred.promise;
});
}
// Tests

View File

@ -13,7 +13,7 @@ function run_test() {
add_task(function() {
let worker = new ChromeWorker(WORKER_SOURCE_URI);
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
worker.onmessage = function(event) {
let data = event.data;
switch (data.kind) {
@ -25,7 +25,7 @@ add_task(function() {
}
return;
case "do_test_complete":
deferred.resolve();
resolve();
worker.terminate();
break;
case "do_print":
@ -35,9 +35,9 @@ add_task(function() {
worker.onerror = function(event) {
let error = new Error(event.message, event.filename, event.lineno);
worker.terminate();
deferred.reject(error);
reject(error);
};
worker.postMessage("START");
return deferred.promise;
});
});

View File

@ -50,7 +50,7 @@ this.read = function(path, options = {}) {
return Promise.reject(new TypeError("Invalid type for option bytes"));
}
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
Internals.read(path,
options,
function onSuccess(success) {
@ -60,11 +60,11 @@ this.read = function(path, options = {}) {
success.executionDurationMS +
(options.outExecutionDuration || 0);
}
deferred.resolve(success.result);
resolve(success.result);
},
function onError(operation, oserror) {
deferred.reject(new SysAll.Error(operation, oserror, path));
reject(new SysAll.Error(operation, oserror, path));
}
);
return deferred.promise;
});
};

View File

@ -86,14 +86,14 @@ var maketest = function(prefix, test) {
*/
var reference_fetch_file = function reference_fetch_file(path, test) {
test.info("Fetching file " + path);
let promise = Promise.defer();
return new Promise((resolve, reject) => {
let file = new FileUtils.File(path);
NetUtil.asyncFetch({
uri: NetUtil.newURI(file),
loadUsingSystemPrincipal: true
}, function(stream, status) {
if (!Components.isSuccessCode(status)) {
promise.reject(status);
reject(status);
return;
}
let result, reject;
@ -104,13 +104,13 @@ var reference_fetch_file = function reference_fetch_file(path, test) {
}
stream.close();
if (reject) {
promise.reject(reject);
reject(reject);
} else {
promise.resolve(result);
resolve(result);
}
});
return promise.promise;
});
};
var reference_dir_contents = function reference_dir_contents(path) {

View File

@ -51,14 +51,14 @@ function add_test_pair(generator) {
*/
function reference_fetch_file(path, test) {
do_print("Fetching file " + path);
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
let file = new FileUtils.File(path);
NetUtil.asyncFetch({
uri: NetUtil.newURI(file),
loadUsingSystemPrincipal: true
}, function(stream, status) {
if (!Components.isSuccessCode(status)) {
deferred.reject(status);
reject(status);
return;
}
let result, reject;
@ -69,13 +69,13 @@ function reference_fetch_file(path, test) {
}
stream.close();
if (reject) {
deferred.reject(reject);
reject(reject);
} else {
deferred.resolve(result);
resolve(result);
}
});
return deferred.promise;
});
};
/**

View File

@ -26,14 +26,14 @@ var EXISTING_FILE = "test_osfile_async_copy.js";
* @resolves {string} The contents of the file.
*/
var reference_fetch_file = function reference_fetch_file(path) {
let promise = Promise.defer();
return new Promise((resolve, reject) => {
let file = new FileUtils.File(path);
NetUtil.asyncFetch({
uri: NetUtil.newURI(file),
loadUsingSystemPrincipal: true
}, function(stream, status) {
if (!Components.isSuccessCode(status)) {
promise.reject(status);
reject(status);
return;
}
let result, reject;
@ -44,13 +44,13 @@ var reference_fetch_file = function reference_fetch_file(path) {
}
stream.close();
if (reject) {
promise.reject(reject);
reject(reject);
} else {
promise.resolve(result);
resolve(result);
}
});
return promise.promise;
});
};
/**

View File

@ -1604,7 +1604,7 @@ this.PlacesUtils = {
* @return {Promise}
*/
setCharsetForURI: function PU_setCharsetForURI(aURI, aCharset) {
let deferred = Promise.defer();
return new Promise(resolve => {
// Delaying to catch issues with asynchronous behavior while waiting
// to implement asynchronous annotations in bug 699844.
@ -1617,10 +1617,10 @@ this.PlacesUtils = {
PlacesUtils.annotations.removePageAnnotation(
aURI, PlacesUtils.CHARSET_ANNO);
}
deferred.resolve();
resolve();
});
return deferred.promise;
});
},
/**
@ -1631,7 +1631,7 @@ this.PlacesUtils = {
* @resolve a character-set or null.
*/
getCharsetForURI: function PU_getCharsetForURI(aURI) {
let deferred = Promise.defer();
return new Promise(resolve => {
Services.tm.dispatchToMainThread(function() {
let charset = null;
@ -1641,10 +1641,10 @@ this.PlacesUtils = {
PlacesUtils.CHARSET_ANNO);
} catch (ex) { }
deferred.resolve(charset);
resolve(charset);
});
return deferred.promise;
});
},
/**
@ -1655,21 +1655,21 @@ this.PlacesUtils = {
* @resolves to the place info object handed to handleResult.
*/
promisePlaceInfo: function PU_promisePlaceInfo(aPlaceIdentifier) {
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
PlacesUtils.asyncHistory.getPlacesInfo(aPlaceIdentifier, {
_placeInfo: null,
handleResult: function handleResult(aPlaceInfo) {
this._placeInfo = aPlaceInfo;
},
handleError: function handleError(aResultCode, aPlaceInfo) {
deferred.reject(new Components.Exception("Error", aResultCode));
reject(new Components.Exception("Error", aResultCode));
},
handleCompletion() {
deferred.resolve(this._placeInfo);
resolve(this._placeInfo);
}
});
return deferred.promise;
});
},
/**
@ -1681,19 +1681,19 @@ this.PlacesUtils = {
* @rejects JavaScript exception if the given url has no associated favicon.
*/
promiseFaviconData(aPageUrl) {
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
PlacesUtils.favicons.getFaviconDataForPage(NetUtil.newURI(aPageUrl),
function(aURI, aDataLen, aData, aMimeType) {
if (aURI) {
deferred.resolve({ uri: aURI,
resolve({ uri: aURI,
dataLen: aDataLen,
data: aData,
mimeType: aMimeType });
} else {
deferred.reject();
reject();
}
});
return deferred.promise;
});
},
/**
@ -1704,19 +1704,19 @@ this.PlacesUtils = {
* @rejects if the given url has no associated favicon.
*/
promiseFaviconLinkUrl(aPageUrl) {
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
if (!(aPageUrl instanceof Ci.nsIURI))
aPageUrl = NetUtil.newURI(aPageUrl);
PlacesUtils.favicons.getFaviconURLForPage(aPageUrl, uri => {
if (uri) {
uri = PlacesUtils.favicons.getFaviconLinkForIcon(uri);
deferred.resolve(uri);
resolve(uri);
} else {
deferred.reject("favicon not found for uri");
reject("favicon not found for uri");
}
});
return deferred.promise;
});
},
/**

View File

@ -67,18 +67,18 @@ add_task(async function maintenance_foreign_count_test() {
await PlacesTestUtils.addVisits(T_URI);
// Adjust the foreign_count for the added entry to an incorrect value
let deferred = Promise.defer();
await new Promise(resolve => {
let stmt = DBConn().createAsyncStatement(
`UPDATE moz_places SET foreign_count = 10 WHERE url_hash = hash(:t_url)
AND url = :t_url `);
stmt.params.t_url = T_URI.spec;
stmt.executeAsync({
handleCompletion() {
deferred.resolve();
resolve();
}
});
stmt.finalize();
await deferred.promise;
});
Assert.equal((await getForeignCountForURL(conn, T_URI)), 10);
// Run maintenance

View File

@ -72,24 +72,24 @@ add_task(async function test_add_visit() {
// Add a visit to the bookmark and wait for the observer.
let visitId;
let deferUpdatePlaces = Promise.defer();
await new Promise((resolve, reject) => {
PlacesUtils.asyncHistory.updatePlaces({
uri: NetUtil.newURI("http://book.ma.rk/"),
visits: [{ transitionType: TRANSITION_TYPED, visitDate: NOW }]
}, {
handleError: function TAV_handleError() {
deferUpdatePlaces.reject(new Error("Unexpected error in adding visit."));
reject(new Error("Unexpected error in adding visit."));
},
handleResult(aPlaceInfo) {
visitId = aPlaceInfo.visits[0].visitId;
},
handleCompletion: function TAV_handleCompletion() {
deferUpdatePlaces.resolve();
resolve();
}
});
// Wait for both the observer and the asynchronous update, in any order.
await deferUpdatePlaces.promise;
});
await observerPromise;
// Check that both asynchronous results are consistent.
@ -127,7 +127,7 @@ add_task(async function shutdown() {
// places-connection-closed.
// Notice this code is not using helpers cause it depends on a very specific
// order, a change in the helpers code could make this test useless.
let deferred = Promise.defer();
await new Promise(resolve => {
Services.obs.addObserver(function onNotification() {
Services.obs.removeObserver(onNotification, "places-will-close-connection");
@ -139,12 +139,12 @@ add_task(async function shutdown() {
.onPageChanged(NetUtil.newURI("http://book.ma.rk/"),
Ci.nsINavHistoryObserver.ATTRIBUTE_FAVICON,
"test", "test");
deferred.resolve(promiseTopicObserved("places-connection-closed"));
resolve(promiseTopicObserved("places-connection-closed"));
});
}, "places-will-close-connection");
shutdownPlaces();
await deferred.promise;
});
});
function run_test() {

View File

@ -53,7 +53,7 @@ add_task(async function test_annos_expire_session() {
items = as.getItemsWithAnnotation("test2");
do_check_eq(items.length, 10);
let deferred = Promise.defer();
await new Promise(resolve => {
waitForConnectionClosed(function() {
let stmt = DBConn(true).createAsyncStatement(
`SELECT id FROM moz_annos
@ -74,10 +74,10 @@ add_task(async function test_annos_expire_session() {
},
handleCompletion(aReason) {
do_check_eq(aReason, Ci.mozIStorageStatementCallback.REASON_FINISHED);
deferred.resolve();
resolve();
}
});
stmt.finalize();
});
await deferred.promise;
});
});

View File

@ -69,7 +69,7 @@ add_task(async function test_replaceFaviconData_validHistoryURI() {
iconsvc.replaceFaviconData(favicon.uri, favicon.data, favicon.data.length,
favicon.mimetype);
let deferSetAndFetchFavicon = Promise.defer();
await new Promise(resolve => {
iconsvc.setAndFetchFaviconForPage(pageURI, favicon.uri, true,
PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
function test_replaceFaviconData_validHistoryURI_check(aURI, aDataLen, aData, aMimeType) {
@ -79,10 +79,10 @@ dump("GOT " + aMimeType + "\n");
pageURI, favicon.mimetype, favicon.data,
function test_replaceFaviconData_validHistoryURI_callback() {
favicon.file.remove(false);
deferSetAndFetchFavicon.resolve();
resolve();
});
}, systemPrincipal);
await deferSetAndFetchFavicon.promise;
});
await PlacesTestUtils.clearHistory();
});
@ -100,7 +100,7 @@ add_task(async function test_replaceFaviconData_overrideDefaultFavicon() {
firstFavicon.uri, secondFavicon.data, secondFavicon.data.length,
secondFavicon.mimetype);
let deferSetAndFetchFavicon = Promise.defer();
await new Promise(resolve => {
iconsvc.setAndFetchFaviconForPage(
pageURI, firstFavicon.uri, true,
PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
@ -111,10 +111,10 @@ add_task(async function test_replaceFaviconData_overrideDefaultFavicon() {
function test_replaceFaviconData_overrideDefaultFavicon_callback() {
firstFavicon.file.remove(false);
secondFavicon.file.remove(false);
deferSetAndFetchFavicon.resolve();
resolve();
});
}, systemPrincipal);
await deferSetAndFetchFavicon.promise;
});
await PlacesTestUtils.clearHistory();
});
@ -128,7 +128,7 @@ add_task(async function test_replaceFaviconData_replaceExisting() {
let firstFavicon = createFavicon("favicon4.png");
let secondFavicon = createFavicon("favicon5.png");
let deferSetAndFetchFavicon = Promise.defer();
await new Promise(resolve => {
iconsvc.setAndFetchFaviconForPage(
pageURI, firstFavicon.uri, true,
PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
@ -146,12 +146,12 @@ add_task(async function test_replaceFaviconData_replaceExisting() {
function test_replaceFaviconData_overrideDefaultFavicon_secondCallback() {
firstFavicon.file.remove(false);
secondFavicon.file.remove(false);
deferSetAndFetchFavicon.resolve();
resolve();
}, systemPrincipal);
});
});
}, systemPrincipal);
await deferSetAndFetchFavicon.promise;
});
await PlacesTestUtils.clearHistory();
});
@ -169,7 +169,7 @@ add_task(async function test_replaceFaviconData_unrelatedReplace() {
unrelatedFavicon.uri, unrelatedFavicon.data, unrelatedFavicon.data.length,
unrelatedFavicon.mimetype);
let deferSetAndFetchFavicon = Promise.defer();
await new Promise(resolve => {
iconsvc.setAndFetchFaviconForPage(
pageURI, favicon.uri, true,
PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
@ -180,10 +180,10 @@ add_task(async function test_replaceFaviconData_unrelatedReplace() {
function test_replaceFaviconData_unrelatedReplace_callback() {
favicon.file.remove(false);
unrelatedFavicon.file.remove(false);
deferSetAndFetchFavicon.resolve();
resolve();
});
}, systemPrincipal);
await deferSetAndFetchFavicon.promise;
});
await PlacesTestUtils.clearHistory();
});
@ -225,7 +225,7 @@ add_task(async function test_replaceFaviconData_twiceReplace() {
firstFavicon.uri, secondFavicon.data, secondFavicon.data.length,
secondFavicon.mimetype);
let deferSetAndFetchFavicon = Promise.defer();
await new Promise(resolve => {
iconsvc.setAndFetchFaviconForPage(
pageURI, firstFavicon.uri, true,
PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
@ -236,10 +236,10 @@ add_task(async function test_replaceFaviconData_twiceReplace() {
function test_replaceFaviconData_twiceReplace_callback() {
firstFavicon.file.remove(false);
secondFavicon.file.remove(false);
deferSetAndFetchFavicon.resolve();
resolve();
}, systemPrincipal);
}, systemPrincipal);
await deferSetAndFetchFavicon.promise;
});
await PlacesTestUtils.clearHistory();
});

View File

@ -72,7 +72,7 @@ add_task(async function test_replaceFaviconDataFromDataURL_validHistoryURI() {
iconsvc.replaceFaviconDataFromDataURL(favicon.uri, createDataURLForFavicon(favicon), 0,
Services.scriptSecurityManager.getSystemPrincipal());
let deferSetAndFetchFavicon = Promise.defer();
await new Promise(resolve => {
iconsvc.setAndFetchFaviconForPage(pageURI, favicon.uri, true,
PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
function test_replaceFaviconDataFromDataURL_validHistoryURI_check(aURI, aDataLen, aData, aMimeType) {
@ -81,10 +81,10 @@ add_task(async function test_replaceFaviconDataFromDataURL_validHistoryURI() {
pageURI, favicon.mimetype, favicon.data,
function test_replaceFaviconDataFromDataURL_validHistoryURI_callback() {
favicon.file.remove(false);
deferSetAndFetchFavicon.resolve();
resolve();
});
}, Services.scriptSecurityManager.getSystemPrincipal());
await deferSetAndFetchFavicon.promise;
});
await PlacesTestUtils.clearHistory();
});
@ -101,7 +101,7 @@ add_task(async function test_replaceFaviconDataFromDataURL_overrideDefaultFavico
iconsvc.replaceFaviconDataFromDataURL(firstFavicon.uri, createDataURLForFavicon(secondFavicon), 0,
Services.scriptSecurityManager.getSystemPrincipal());
let deferSetAndFetchFavicon = Promise.defer();
await new Promise(resolve => {
iconsvc.setAndFetchFaviconForPage(
pageURI, firstFavicon.uri, true,
PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
@ -112,10 +112,10 @@ add_task(async function test_replaceFaviconDataFromDataURL_overrideDefaultFavico
function test_replaceFaviconDataFromDataURL_overrideDefaultFavicon_callback() {
firstFavicon.file.remove(false);
secondFavicon.file.remove(false);
deferSetAndFetchFavicon.resolve();
resolve();
});
}, Services.scriptSecurityManager.getSystemPrincipal());
await deferSetAndFetchFavicon.promise;
});
await PlacesTestUtils.clearHistory();
});
@ -129,7 +129,7 @@ add_task(async function test_replaceFaviconDataFromDataURL_replaceExisting() {
let firstFavicon = createFavicon("favicon4.png");
let secondFavicon = createFavicon("favicon5.png");
let deferSetAndFetchFavicon = Promise.defer();
await new Promise(resolve => {
iconsvc.setAndFetchFaviconForPage(
pageURI, firstFavicon.uri, true,
PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
@ -145,11 +145,11 @@ add_task(async function test_replaceFaviconDataFromDataURL_replaceExisting() {
function test_replaceFaviconDataFromDataURL_replaceExisting_secondCallback() {
firstFavicon.file.remove(false);
secondFavicon.file.remove(false);
deferSetAndFetchFavicon.resolve();
resolve();
});
});
}, Services.scriptSecurityManager.getSystemPrincipal());
await deferSetAndFetchFavicon.promise;
});
await PlacesTestUtils.clearHistory();
});
@ -166,7 +166,7 @@ add_task(async function test_replaceFaviconDataFromDataURL_unrelatedReplace() {
iconsvc.replaceFaviconDataFromDataURL(unrelatedFavicon.uri, createDataURLForFavicon(unrelatedFavicon), 0,
Services.scriptSecurityManager.getSystemPrincipal());
let deferSetAndFetchFavicon = Promise.defer();
await new Promise(resolve => {
iconsvc.setAndFetchFaviconForPage(
pageURI, favicon.uri, true,
PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
@ -177,10 +177,10 @@ add_task(async function test_replaceFaviconDataFromDataURL_unrelatedReplace() {
function test_replaceFaviconDataFromDataURL_unrelatedReplace_callback() {
favicon.file.remove(false);
unrelatedFavicon.file.remove(false);
deferSetAndFetchFavicon.resolve();
resolve();
});
}, Services.scriptSecurityManager.getSystemPrincipal());
await deferSetAndFetchFavicon.promise;
});
await PlacesTestUtils.clearHistory();
});
@ -229,7 +229,7 @@ add_task(async function test_replaceFaviconDataFromDataURL_twiceReplace() {
iconsvc.replaceFaviconDataFromDataURL(firstFavicon.uri, createDataURLForFavicon(secondFavicon), 0,
Services.scriptSecurityManager.getSystemPrincipal());
let deferSetAndFetchFavicon = Promise.defer();
await new Promise(resolve => {
iconsvc.setAndFetchFaviconForPage(
pageURI, firstFavicon.uri, true,
PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
@ -240,10 +240,10 @@ add_task(async function test_replaceFaviconDataFromDataURL_twiceReplace() {
function test_replaceFaviconDataFromDataURL_twiceReplace_callback() {
firstFavicon.file.remove(false);
secondFavicon.file.remove(false);
deferSetAndFetchFavicon.resolve();
resolve();
});
}, Services.scriptSecurityManager.getSystemPrincipal());
await deferSetAndFetchFavicon.promise;
});
await PlacesTestUtils.clearHistory();
});
@ -263,7 +263,7 @@ add_task(async function test_replaceFaviconDataFromDataURL_afterRegularAssign()
iconsvc.replaceFaviconDataFromDataURL(firstFavicon.uri, createDataURLForFavicon(secondFavicon), 0,
Services.scriptSecurityManager.getSystemPrincipal());
let deferSetAndFetchFavicon = Promise.defer();
await new Promise(resolve => {
iconsvc.setAndFetchFaviconForPage(
pageURI, firstFavicon.uri, true,
PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
@ -274,10 +274,10 @@ add_task(async function test_replaceFaviconDataFromDataURL_afterRegularAssign()
function test_replaceFaviconDataFromDataURL_afterRegularAssign_callback() {
firstFavicon.file.remove(false);
secondFavicon.file.remove(false);
deferSetAndFetchFavicon.resolve();
resolve();
});
}, Services.scriptSecurityManager.getSystemPrincipal());
await deferSetAndFetchFavicon.promise;
});
await PlacesTestUtils.clearHistory();
});
@ -297,7 +297,7 @@ add_task(async function test_replaceFaviconDataFromDataURL_beforeRegularAssign()
firstFavicon.uri, secondFavicon.data, secondFavicon.data.length,
secondFavicon.mimetype);
let deferSetAndFetchFavicon = Promise.defer();
await new Promise(resolve => {
iconsvc.setAndFetchFaviconForPage(
pageURI, firstFavicon.uri, true,
PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
@ -308,10 +308,10 @@ add_task(async function test_replaceFaviconDataFromDataURL_beforeRegularAssign()
function test_replaceFaviconDataFromDataURL_beforeRegularAssign_callback() {
firstFavicon.file.remove(false);
secondFavicon.file.remove(false);
deferSetAndFetchFavicon.resolve();
resolve();
});
}, Services.scriptSecurityManager.getSystemPrincipal());
await deferSetAndFetchFavicon.promise;
});
await PlacesTestUtils.clearHistory();
});

View File

@ -808,13 +808,13 @@ NavHistoryResultObserver.prototype = {
* @rejects JavaScript exception.
*/
function promiseIsURIVisited(aURI) {
let deferred = Promise.defer();
return new Promise(resolve => {
PlacesUtils.asyncHistory.isURIVisited(aURI, function(unused, aIsVisited) {
deferred.resolve(aIsVisited);
resolve(aIsVisited);
});
return deferred.promise;
});
}
function checkBookmarkObject(info) {

View File

@ -226,7 +226,7 @@ add_task(async function test_frecency() {
do_check_eq(numSearchesStarted, 1);
};
let deferred = Promise.defer();
await new Promise(resolve => {
input.onSearchComplete = function() {
do_check_eq(numSearchesStarted, 1);
do_check_eq(controller.searchStatus,
@ -253,10 +253,10 @@ add_task(async function test_frecency() {
do_check_eq(getFrecency(searchURL), getFrecency(expectURL));
}
}
deferred.resolve();
resolve();
};
controller.startSearch(searchTerm);
await deferred.promise;
});
});

View File

@ -113,21 +113,21 @@ add_task(async function test_parseSubmissionURL_basic() {
});
function promiseDefaultSearchEngine() {
let deferred = Promise.defer();
return new Promise(resolve => {
Services.search.init( () => {
deferred.resolve(Services.search.defaultEngine);
resolve(Services.search.defaultEngine);
});
});
return deferred.promise;
}
function promiseSearchTopic(expectedVerb) {
let deferred = Promise.defer();
return new Promise(resolve => {
Services.obs.addObserver( function observe(subject, topic, verb) {
do_print("browser-search-engine-modified: " + verb);
if (verb == expectedVerb) {
Services.obs.removeObserver(observe, "browser-search-engine-modified");
deferred.resolve();
resolve();
}
}, "browser-search-engine-modified");
return deferred.promise;
});
}

View File

@ -58,27 +58,27 @@ add_task(async function test_nsNavHistory_DecayFrecency_and_nsNavHistory_FixInva
});
function onFrecencyChanged(expectedURI) {
let deferred = Promise.defer();
return new Promise(resolve => {
let obs = new NavHistoryObserver();
obs.onFrecencyChanged =
(uri, newFrecency, guid, hidden, visitDate) => {
PlacesUtils.history.removeObserver(obs);
do_check_true(!!uri);
do_check_true(uri.equals(expectedURI));
deferred.resolve();
resolve();
};
PlacesUtils.history.addObserver(obs);
return deferred.promise;
});
}
function onManyFrecenciesChanged() {
let deferred = Promise.defer();
return new Promise(resolve => {
let obs = new NavHistoryObserver();
obs.onManyFrecenciesChanged = () => {
PlacesUtils.history.removeObserver(obs);
do_check_true(true);
deferred.resolve();
resolve();
};
PlacesUtils.history.addObserver(obs);
return deferred.promise;
});
}

View File

@ -2,7 +2,7 @@
http://creativecommons.org/publicdomain/zero/1.0/ */
function promiseGetPlacesInfo(aPlacesIdentifiers) {
let deferred = Promise.defer();
return new Promise(resolve => {
PlacesUtils.asyncHistory.getPlacesInfo(aPlacesIdentifiers, {
_results: [],
_errors: [],
@ -14,11 +14,11 @@ function promiseGetPlacesInfo(aPlacesIdentifiers) {
this._errors.push({ resultCode: aResultCode, info: aPlaceInfo });
},
handleCompletion: function handleCompletion() {
deferred.resolve({ errors: this._errors, results: this._results });
resolve({ errors: this._errors, results: this._results });
}
});
return deferred.promise;
});
}
function ensurePlacesInfoObjectsAreEqual(a, b) {

View File

@ -7,7 +7,7 @@
var mDBConn = DBConn();
function promiseOnClearHistoryObserved() {
let deferred = Promise.defer();
return new Promise(resolve => {
let historyObserver = {
onBeginUpdateBatch() {},
@ -20,7 +20,7 @@ function promiseOnClearHistoryObserved() {
onClearHistory() {
PlacesUtils.history.removeObserver(this, false);
deferred.resolve();
resolve();
},
QueryInterface: XPCOMUtils.generateQI([
@ -28,7 +28,7 @@ function promiseOnClearHistoryObserved() {
])
}
PlacesUtils.history.addObserver(historyObserver);
return deferred.promise;
});
}
// This global variable is a promise object, initialized in run_test and waited

View File

@ -10,17 +10,17 @@ const NHQO = Ci.nsINavHistoryQueryOptions;
* Waits for onItemVisited notifications to be received.
*/
function promiseOnItemVisited() {
let defer = Promise.defer();
return new Promise(resolve => {
let bookmarksObserver = {
__proto__: NavBookmarkObserver.prototype,
onItemVisited: function BO_onItemVisited() {
PlacesUtils.bookmarks.removeObserver(this);
// Enqueue to be sure that all onItemVisited notifications ran.
do_execute_soon(defer.resolve);
do_execute_soon(resolve);
}
};
PlacesUtils.bookmarks.addObserver(bookmarksObserver);
return defer.promise;
});
}
function run_test() {

View File

@ -78,9 +78,9 @@ function waitForCondition(condition, nextTest, errorMsg, retryTimes) {
}
function promiseWaitForCondition(aConditionFn) {
let deferred = Promise.defer();
waitForCondition(aConditionFn, deferred.resolve, "Condition didn't pass.");
return deferred.promise;
return new Promise(resolve => {
waitForCondition(aConditionFn, resolve, "Condition didn't pass.");
});
}
function is_element_visible(element, msg) {

View File

@ -8,42 +8,42 @@ var dbConnection; // used for deleted table tests
Cu.import("resource://gre/modules/Promise.jsm");
function countDeletedEntries(expected) {
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
let stmt = dbConnection.createAsyncStatement("SELECT COUNT(*) AS numEntries FROM moz_deleted_formhistory");
stmt.executeAsync({
handleResult(resultSet) {
do_check_eq(expected, resultSet.getNextRow().getResultByName("numEntries"));
deferred.resolve();
resolve();
},
handleError(error) {
do_throw("Error occurred counting deleted entries: " + error);
deferred.reject();
reject();
},
handleCompletion() {
stmt.finalize();
}
});
return deferred.promise;
});
}
function checkTimeDeleted(guid, checkFunction) {
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
let stmt = dbConnection.createAsyncStatement("SELECT timeDeleted FROM moz_deleted_formhistory WHERE guid = :guid");
stmt.params.guid = guid;
stmt.executeAsync({
handleResult(resultSet) {
checkFunction(resultSet.getNextRow().getResultByName("timeDeleted"));
deferred.resolve();
resolve();
},
handleError(error) {
do_throw("Error occurred getting deleted entries: " + error);
deferred.reject();
reject();
},
handleCompletion() {
stmt.finalize();
}
});
return deferred.promise;
});
}
function promiseUpdateEntry(op, name, value) {
@ -73,23 +73,23 @@ function promiseUpdate(change) {
}
function promiseSearchEntries(terms, params) {
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
let results = [];
FormHistory.search(terms, params,
{ handleResult: result => results.push(result),
handleError(error) {
do_throw("Error occurred searching form history: " + error);
deferred.reject(error);
reject(error);
},
handleCompletion(reason) { if (!reason) deferred.resolve(results); }
handleCompletion(reason) { if (!reason) resolve(results); }
});
});
return deferred.promise;
}
function promiseCountEntries(name, value, checkFn) {
let deferred = Promise.defer();
countEntries(name, value, function(result) { checkFn(result); deferred.resolve(); } );
return deferred.promise;
return new Promise(resolve => {
countEntries(name, value, function(result) { checkFn(result); resolve(); } );
});
}
add_task(async function() {

View File

@ -1428,22 +1428,22 @@ Engine.prototype = {
* succeeds.
*/
_retrieveSearchXMLData: function SRCH_ENG__retrieveSearchXMLData(aURL) {
let deferred = Promise.defer();
return new Promise(resolve => {
let request = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].
createInstance(Ci.nsIXMLHttpRequest);
request.overrideMimeType("text/xml");
request.onload = (aEvent) => {
let responseXML = aEvent.target.responseXML;
this._data = responseXML.documentElement;
deferred.resolve();
resolve();
};
request.onerror = function(aEvent) {
deferred.resolve();
resolve();
};
request.open("GET", aURL, true);
request.send();
return deferred.promise;
});
},
_initFromURISync: function SRCH_ENG_initFromURISync(uri) {

View File

@ -78,16 +78,16 @@ add_task(async function add_test_engines() {
// Begin tests
add_task(async function simple_no_result_callback() {
let deferred = Promise.defer();
await new Promise(resolve => {
let controller = new SearchSuggestionController((result) => {
do_check_eq(result.term, "no remote");
do_check_eq(result.local.length, 0);
do_check_eq(result.remote.length, 0);
deferred.resolve();
resolve();
});
controller.fetch("no remote", false, getEngine);
await deferred.promise;
});
});
add_task(async function simple_no_result_callback_and_promise() {
@ -551,7 +551,7 @@ add_task(async function test_userContextId() {
// Helpers
function updateSearchHistory(operation, value) {
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
FormHistory.update({
op: operation,
fieldname: "searchbar-history",
@ -560,12 +560,12 @@ function updateSearchHistory(operation, value) {
{
handleError(error) {
do_throw("Error occurred updating form history: " + error);
deferred.reject(error);
reject(error);
},
handleCompletion(reason) {
if (!reason)
deferred.resolve();
resolve();
}
});
return deferred.promise;
});
}

View File

@ -82,17 +82,17 @@ const TaskUtils = {
* @reject {DOMError} In case of error, the underlying DOMError.
*/
readBlob: function readBlob(blob) {
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
let reader = new FileReader();
reader.onloadend = function onloadend() {
if (reader.readyState != FileReader.DONE) {
deferred.reject(reader.error);
reject(reader.error);
} else {
deferred.resolve(reader.result);
resolve(reader.result);
}
};
reader.readAsArrayBuffer(blob);
return deferred.promise;
});
}
};
@ -186,16 +186,16 @@ this.PageThumbs = {
return null;
}
let deferred = Promise.defer();
return new Promise(resolve => {
let canvas = this.createCanvas(aBrowser.contentWindow);
this.captureToCanvas(aBrowser, canvas, () => {
canvas.toBlob(blob => {
deferred.resolve(blob, this.contentType);
resolve(blob, this.contentType);
});
});
return deferred.promise;
});
},
/**
@ -307,7 +307,7 @@ this.PageThumbs = {
* @return a promise
*/
_captureRemoteThumbnail(aBrowser, aWidth, aHeight, aArgs) {
let deferred = Promise.defer();
return new Promise(resolve => {
// The index we send with the request so we can identify the
// correct response.
@ -335,7 +335,7 @@ this.PageThumbs = {
thumbnail.height = image.naturalHeight;
let ctx = thumbnail.getContext("2d");
ctx.drawImage(image, 0, 0);
deferred.resolve({
resolve({
thumbnail
});
}
@ -355,7 +355,7 @@ this.PageThumbs = {
additionalArgs: aArgs
});
return deferred.promise;
});
},
/**

View File

@ -29,7 +29,7 @@ function readFileToString(aFilename) {
// Registers a table for which to serve update chunks. Returns a promise that
// resolves when that chunk has been downloaded.
function registerTableUpdate(aTable, aFilename) {
let deferred = Promise.defer();
return new Promise(resolve => {
// If we haven't been given an update for this table yet, add it to the map
if (!(aTable in gTables)) {
gTables[aTable] = [];
@ -51,9 +51,9 @@ function registerTableUpdate(aTable, aFilename) {
"application/vnd.google.safebrowsing-update", false);
response.setStatusLine(request.httpVersion, 200, "OK");
response.bodyOutputStream.write(contents, contents.length);
deferred.resolve(contents);
resolve(contents);
});
});
return deferred.promise;
}
// Construct a response with redirect urls.

View File

@ -685,18 +685,18 @@ function promiseTargetFile(aFpP, /* optional */ aSkipPrompt, /* optional */ aRel
// We must prompt for the file name explicitly.
// If we must prompt because we were asked to...
let deferred = Promise.defer();
let file = await new Promise(resolve => {
if (useDownloadDir) {
// Keep async behavior in both branches
Services.tm.dispatchToMainThread(function() {
deferred.resolve(null);
resolve(null);
});
} else {
downloadLastDir.getFileAsync(aRelatedURI, function getFileAsyncCB(aFile) {
deferred.resolve(aFile);
resolve(aFile);
});
}
let file = await deferred.promise;
});
if (file && (await OS.File.exists(file.path))) {
dir = file;
dirExists = true;
@ -729,11 +729,11 @@ function promiseTargetFile(aFpP, /* optional */ aSkipPrompt, /* optional */ aRel
}
}
let deferComplete = Promise.defer();
let result = await new Promise(resolve => {
fp.open(function(aResult) {
deferComplete.resolve(aResult);
resolve(aResult);
});
});
let result = await deferComplete.promise;
if (result == Components.interfaces.nsIFilePicker.returnCancel || !fp.file) {
return false;
}

View File

@ -198,7 +198,7 @@ add_task(async function() {
});
function promiseFindFinished(searchText, highlightOn) {
let deferred = Promise.defer();
return new Promise(resolve => {
let findbar = gBrowser.getFindBar();
findbar.startFind(findbar.FIND_NORMAL);
@ -224,7 +224,7 @@ function promiseFindFinished(searchText, highlightOn) {
info("Result listener not called, timeout reached.");
clearTimeout(findTimeout);
findbar.browser.finder.removeResultListener(resultListener);
deferred.resolve();
resolve();
}
resultListener = {
@ -234,7 +234,7 @@ function promiseFindFinished(searchText, highlightOn) {
findbar._find();
});
return deferred.promise;
});
}
function promiseRemotenessChange(tab, shouldBeRemote) {

View File

@ -27,9 +27,9 @@ function closeFindbarAndWait(findbar) {
}
function pushPrefs(...aPrefs) {
let deferred = Promise.defer();
SpecialPowers.pushPrefEnv({"set": aPrefs}, deferred.resolve);
return deferred.promise;
return new Promise(resolve => {
SpecialPowers.pushPrefEnv({"set": aPrefs}, resolve);
});
}
/**

View File

@ -49,7 +49,7 @@ let observer = {
// count of reflows isn't what is expected, it causes a test failure and logs
// the stack trace of all seen reflows.
function countReflows(testfn, expected) {
let deferred = Promise.defer();
return new Promise(resolve => {
observer.reflows = [];
let docShell = panel.ownerGlobal
.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
@ -62,19 +62,19 @@ function countReflows(testfn, expected) {
if (observer.reflows.length != expected) {
SimpleTest.info("stack traces of reflows:\n" + observer.reflows.join("\n") + "\n");
}
deferred.resolve();
resolve();
});
});
return deferred.promise
}
function openPopup() {
let deferred = Promise.defer();
return new Promise(resolve => {
panel.addEventListener("popupshown", function popupshown() {
panel.removeEventListener("popupshown", popupshown);
deferred.resolve();
resolve();
});
panel.openPopup(anchor, "before_start");
return deferred.promise
});
}
// ********************

View File

@ -23,7 +23,7 @@ add_task(async function test_main_process_crash() {
Assert.ok(cm, "CrashManager available.");
let basename;
let deferred = Promise.defer();
let count = await new Promise((resolve, reject) => {
do_crash(
function() {
// TelemetrySession setup will trigger the session annotation
@ -36,11 +36,11 @@ add_task(async function test_main_process_crash() {
(minidump, extra) => {
basename = minidump.leafName;
cm._eventsDirs = [getEventDir()];
cm.aggregateEventsFiles().then(deferred.resolve, deferred.reject);
cm.aggregateEventsFiles().then(resolve, reject);
},
true);
let count = await deferred.promise;
});
Assert.equal(count, 1, "A single crash event file was seen.");
let crashes = await cm.getCrashes();
Assert.equal(crashes.length, 1);

View File

@ -61,12 +61,12 @@ function uri(aURIString) {
* @rejects JavaScript exception.
*/
function promiseIsURIVisited(aURI) {
let deferred = Promise.defer();
return new Promise(resolve => {
PlacesUtils.asyncHistory.isURIVisited(aURI, function(unused, aIsVisited) {
deferred.resolve(aIsVisited);
resolve(aIsVisited);
});
return deferred.promise;
});
}
/**
@ -209,13 +209,13 @@ function check_permission_exists(aURI, aExists) {
* The URI to add a preference for.
*/
function add_preference(aURI) {
let deferred = Promise.defer();
return new Promise(resolve => {
let cp = Cc["@mozilla.org/content-pref/service;1"].
getService(Ci.nsIContentPrefService2);
cp.set(aURI.spec, PREFERENCE_NAME, "foo", null, {
handleCompletion: () => deferred.resolve()
handleCompletion: () => resolve()
});
});
return deferred.promise;
}
/**
@ -225,15 +225,15 @@ function add_preference(aURI) {
* The URI to check if a preference exists.
*/
function preference_exists(aURI) {
let deferred = Promise.defer();
return new Promise(resolve => {
let cp = Cc["@mozilla.org/content-pref/service;1"].
getService(Ci.nsIContentPrefService2);
let exists = false;
cp.getByDomainAndName(aURI.spec, PREFERENCE_NAME, null, {
handleResult: () => exists = true,
handleCompletion: () => deferred.resolve(exists)
handleCompletion: () => resolve(exists)
});
});
return deferred.promise;
}
// Test Functions
@ -374,7 +374,7 @@ async function test_permission_manager_not_cleared_with_uri_contains_domain() {
}
function waitForPurgeNotification() {
let deferred = Promise.defer();
return new Promise(resolve => {
let observer = {
observe(aSubject, aTopic, aData) {
@ -383,13 +383,13 @@ function waitForPurgeNotification() {
// the DOMStorage clean-up is also listening to this same observer
// which is run synchronously.
Services.tm.dispatchToMainThread(function() {
deferred.resolve();
resolve();
});
}
};
Services.obs.addObserver(observer, "browser:purge-domain-data");
return deferred.promise;
});
}
// Content Preferences

View File

@ -38,7 +38,7 @@ const EXTRACTION_BUFFER = 1024 * 512;
* The open OS.File instance to write to.
*/
function saveStreamAsync(aPath, aStream, aFile) {
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
// Read the input stream on a background thread
let sts = Cc["@mozilla.org/network/stream-transport-service;1"].
@ -59,10 +59,10 @@ function saveStreamAsync(aPath, aStream, aFile) {
}
aFile.close().then(function() {
deferred.reject(error);
reject(error);
}, function(e) {
Cu.reportError("Failed to close file for " + aPath);
deferred.reject(error);
reject(error);
});
}
@ -77,7 +77,7 @@ function saveStreamAsync(aPath, aStream, aFile) {
}, readFailed);
} catch (e) {
if (e.result == Cr.NS_BASE_STREAM_CLOSED)
deferred.resolve(aFile.close());
resolve(aFile.close());
else
readFailed(e);
}
@ -85,7 +85,7 @@ function saveStreamAsync(aPath, aStream, aFile) {
input.asyncWait(readData, 0, 0, Services.tm.currentThread);
return deferred.promise;
});
}

View File

@ -28,9 +28,9 @@ const T = 100;
* Waits for the specified timeout before resolving the returned promise.
*/
function promiseTimeout(aTimeoutMs) {
let deferred = Promise.defer();
do_timeout(aTimeoutMs, deferred.resolve);
return deferred.promise;
return new Promise(resolve => {
do_timeout(aTimeoutMs, resolve);
});
}
function run_test() {

View File

@ -16,18 +16,18 @@ Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://services-common/async.js");
function sleep(ms) {
let deferred = Promise.defer();
return new Promise(resolve => {
let timer = Cc["@mozilla.org/timer;1"]
.createInstance(Ci.nsITimer);
timer.initWithCallback({
notify() {
deferred.resolve();
resolve();
},
}, ms, timer.TYPE_ONE_SHOT);
return deferred.promise;
});
}
// When testing finalization, use this to tell Sqlite.jsm to not throw
@ -255,15 +255,15 @@ add_task(async function test_close_cached() {
add_task(async function test_execute_invalid_statement() {
let c = await getDummyDatabase("invalid_statement");
let deferred = Promise.defer();
await new Promise(resolve => {
do_check_eq(c._connectionData._anonymousStatements.size, 0);
c.execute("SELECT invalid FROM unknown").then(do_throw, function onError(error) {
deferred.resolve();
resolve();
});
await deferred.promise;
});
// Ensure we don't leak the statement instance.
do_check_eq(c._connectionData._anonymousStatements.size, 0);

View File

@ -42,18 +42,18 @@ async function getDummyDatabase(name, extraOptions = {}) {
}
function sleep(ms) {
let deferred = Promise.defer();
return new Promise(resolve => {
let timer = Cc["@mozilla.org/timer;1"]
.createInstance(Ci.nsITimer);
timer.initWithCallback({
notify() {
deferred.resolve();
resolve();
},
}, ms, timer.TYPE_ONE_SHOT);
return deferred.promise;
});
}
function run_test() {

View File

@ -27,9 +27,9 @@ XPCOMUtils.defineLazyModuleGetter(this, "Task",
* posted on the event loop of the main thread is processed.
*/
function promiseResolvedLater(aValue) {
let deferred = Promise.defer();
Services.tm.dispatchToMainThread(() => deferred.resolve(aValue));
return deferred.promise;
return new Promise(resolve => {
Services.tm.dispatchToMainThread(() => resolve(aValue));
});
}
////////////////////////////////////////////////////////////////////////////////

View File

@ -39,11 +39,11 @@ this.AddonManagerTesting = {
* @return Promise<restartRequired>
*/
uninstallAddonByID(id) {
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
AddonManager.getAddonByID(id, (addon) => {
if (!addon) {
deferred.reject(new Error("Add-on is not known: " + id));
reject(new Error("Add-on is not known: " + id));
return;
}
@ -55,7 +55,7 @@ this.AddonManagerTesting = {
if (needsRestart) {
AddonManager.removeAddonListener(listener);
deferred.resolve(true);
resolve(true);
}
},
@ -65,7 +65,7 @@ this.AddonManagerTesting = {
}
AddonManager.removeAddonListener(listener);
deferred.resolve(false);
resolve(false);
},
onOperationCancelled(addon) {
@ -74,7 +74,7 @@ this.AddonManagerTesting = {
}
AddonManager.removeAddonListener(listener);
deferred.reject(new Error("Uninstall cancelled."));
reject(new Error("Uninstall cancelled."));
},
};
@ -82,7 +82,7 @@ this.AddonManagerTesting = {
addon.uninstall();
});
return deferred.promise;
});
},
/**
@ -91,10 +91,10 @@ this.AddonManagerTesting = {
* @return Promise<addon>
*/
installXPIFromURL(url, hash, name, iconURL, version) {
let deferred = Promise.defer();
return new Promise((resolve, reject) => {
AddonManager.getInstallForURL(url, (install) => {
let fail = () => { deferred.reject(new Error("Add-on install failed.")) };
let fail = () => { reject(new Error("Add-on install failed.")) };
let listener = {
onDownloadCancelled: fail,
@ -102,7 +102,7 @@ this.AddonManagerTesting = {
onInstallCancelled: fail,
onInstallFailed: fail,
onInstallEnded(install, addon) {
deferred.resolve(addon);
resolve(addon);
},
};
@ -110,6 +110,6 @@ this.AddonManagerTesting = {
install.install();
}, "application/x-xpinstall", hash, name, iconURL, version);
return deferred.promise;
});
},
};

View File

@ -46,19 +46,19 @@ var ao10 = { file: "browser_bug557956_10", id: "bug557956-10@tests.mozilla.org"}
// Return a promise that resolves after the specified delay in MS
function delayMS(aDelay) {
let deferred = Promise.defer();
setTimeout(deferred.resolve, aDelay);
return deferred.promise;
return new Promise(resolve => {
setTimeout(resolve, aDelay);
});
}
// Return a promise that resolves when the specified observer topic is notified
function promise_observer(aTopic) {
let deferred = Promise.defer();
return new Promise(resolve => {
Services.obs.addObserver(function observe(aSubject, aObsTopic, aData) {
Services.obs.removeObserver(arguments.callee, aObsTopic);
deferred.resolve([aSubject, aData]);
resolve([aSubject, aData]);
}, aTopic);
return deferred.promise;
});
}
// Install a set of addons using a bogus update URL so that we can force
@ -66,7 +66,7 @@ function promise_observer(aTopic) {
// @param aUpdateURL The real update URL to use after the add-ons are installed
function promise_install_test_addons(aAddonList, aUpdateURL) {
info("Starting add-on installs");
let deferred = Promise.defer();
return new Promise(resolve => {
// Use a blank update URL
Services.prefs.setCharPref(PREF_UPDATEURL, TESTROOT + "missing.rdf");
@ -85,7 +85,7 @@ function promise_install_test_addons(aAddonList, aUpdateURL) {
info("Done add-on installs");
// Switch to the test update URL
Services.prefs.setCharPref(PREF_UPDATEURL, aUpdateURL);
deferred.resolve();
resolve();
}
}
};
@ -96,21 +96,21 @@ function promise_install_test_addons(aAddonList, aUpdateURL) {
}
});
return deferred.promise;
});
}
function promise_addons_by_ids(aAddonIDs) {
info("promise_addons_by_ids " + aAddonIDs.toSource());
let deferred = Promise.defer();
AddonManager.getAddonsByIDs(aAddonIDs, deferred.resolve);
return deferred.promise;
return new Promise(resolve => {
AddonManager.getAddonsByIDs(aAddonIDs, resolve);
});
}
async function promise_uninstall_test_addons() {
info("Starting add-on uninstalls");
let addons = await promise_addons_by_ids([ao1.id, ao2.id, ao3.id, ao4.id, ao5.id,
ao6.id, ao7.id, ao8.id, ao9.id, ao10.id]);
let deferred = Promise.defer();
await new Promise(resolve => {
let uninstallCount = addons.length;
let listener = {
onUninstalled(aAddon) {
@ -120,7 +120,7 @@ async function promise_uninstall_test_addons() {
if (--uninstallCount == 0) {
info("Done add-on uninstalls");
AddonManager.removeAddonListener(listener);
deferred.resolve();
resolve();
}
}};
AddonManager.addAddonListener(listener);
@ -130,13 +130,13 @@ async function promise_uninstall_test_addons() {
else
listener.onUninstalled(null);
}
await deferred.promise;
});
}
// Returns promise{window}, resolves with a handle to the compatibility
// check window
function promise_open_compatibility_window(aInactiveAddonIds) {
let deferred = Promise.defer();
return new Promise(resolve => {
// This will reset the longer timeout multiplier to 2 which will give each
// test that calls open_compatibility_window a minimum of 60 seconds to
// complete.
@ -169,32 +169,32 @@ function promise_open_compatibility_window(aInactiveAddonIds) {
dump("Compatibility dialog closed\n");
}, {once: true});
deferred.resolve(win);
resolve(win);
});
});
return deferred.promise;
}
function promise_window_close(aWindow) {
let deferred = Promise.defer();
return new Promise(resolve => {
aWindow.addEventListener("unload", function() {
deferred.resolve(aWindow);
resolve(aWindow);
}, {once: true});
return deferred.promise;
});
}
function promise_page(aWindow, aPageId) {
let deferred = Promise.defer();
return new Promise(resolve => {
var page = aWindow.document.getElementById(aPageId);
if (aWindow.document.getElementById("updateWizard").currentPage === page) {
deferred.resolve(aWindow);
resolve(aWindow);
} else {
page.addEventListener("pageshow", function() {
executeSoon(function() {
deferred.resolve(aWindow);
resolve(aWindow);
});
}, {once: true});
}
return deferred.promise;
});
}
// These add-ons became inactive during the upgrade
@ -263,9 +263,9 @@ add_task(async function cancel_during_repopulate() {
ok(!repo.AddonRepository.isSearching, "Background installs are done");
// There should be no active updates
let getInstalls = Promise.defer();
AddonManager.getAllInstalls(getInstalls.resolve);
let installs = await getInstalls.promise;
let installs = await new Promise(resolve => {
AddonManager.getAllInstalls(resolve);
});
is(installs.length, 0, "There should be no active installs after background installs are done");
// addon8 should have updated in the background,
@ -332,9 +332,9 @@ add_task(async function cancel_during_findUpdates() {
ok(!a8.isCompatible, "addon8 should not have been upgraded");
ok(a9.isCompatible, "addon9 should have been upgraded");
let getInstalls = Promise.defer();
AddonManager.getAllInstalls(getInstalls.resolve);
let installs = await getInstalls.promise;
let installs = await new Promise(resolve => {
AddonManager.getAllInstalls(resolve);
});
is(installs.length, 0, "There should be no active installs after the dialog is cancelled 2");
info("findUpdates done");
@ -393,9 +393,9 @@ add_task(async function cancel_mismatch() {
ok(a9.isCompatible, "addon9 should have been upgraded");
// Make sure there are no pending addon installs
let pInstalls = Promise.defer();
AddonManager.getAllInstalls(pInstalls.resolve);
let installs = await pInstalls.promise;
let installs = await new Promise(resolve => {
AddonManager.getAllInstalls(resolve);
});
ok(installs.length == 0, "No remaining add-on installs (" + installs.toSource() + ")");
await promise_uninstall_test_addons();
@ -440,9 +440,9 @@ add_task(async function cancel_mismatch_no_updates() {
ok(a6.isCompatible, "addon6 should have become compatible");
// Make sure there are no pending addon installs
let pInstalls = Promise.defer();
AddonManager.getAllInstalls(pInstalls.resolve);
let installs = await pInstalls.promise;
let installs = await new Promise(resolve => {
AddonManager.getAllInstalls(resolve);
});
ok(installs.length == 0, "No remaining add-on installs (" + installs.toSource() + ")");
await promise_uninstall_test_addons();

View File

@ -19,11 +19,11 @@ const SEC_IN_ONE_DAY = 24 * 60 * 60;
const MS_IN_ONE_DAY = SEC_IN_ONE_DAY * 1000;
function getExperimentAddons() {
let deferred = Promise.defer();
return new Promise(resolve => {
AddonManager.getAddonsByTypes(["experiment"], (addons) => {
deferred.resolve(addons);
resolve(addons);
});
});
return deferred.promise;
}
function patchPolicy(policy, data) {
@ -47,9 +47,9 @@ function openDetailsView(aId) {
EventUtils.synthesizeMouseAtCenter(item, { clickCount: 1 }, gManagerWindow);
EventUtils.synthesizeMouseAtCenter(item, { clickCount: 2 }, gManagerWindow);
let deferred = Promise.defer();
wait_for_view_load(gManagerWindow, deferred.resolve);
return deferred.promise;
return new Promise(resolve => {
wait_for_view_load(gManagerWindow, resolve);
});
}
function clickRemoveButton(addonElement) {
@ -279,7 +279,7 @@ add_task(async function testActivateExperiment() {
await gExperiments.updateManifest();
info("Experiments update complete.");
let deferred = Promise.defer();
await new Promise(resolve => {
gHttpServer.stop(() => {
gHttpServer = null;
@ -287,11 +287,11 @@ add_task(async function testActivateExperiment() {
AddonManager.getAddonByID("test-experiment1@experiments.mozilla.org", (addon) => {
Assert.ok(addon, "Add-on installed via Experiments manager.");
deferred.resolve();
resolve();
});
});
await deferred.promise;
});
Assert.ok(gCategoryUtilities.isTypeVisible, "experiment", "Experiment tab visible.");
await gCategoryUtilities.openType("experiment");
@ -318,11 +318,11 @@ add_task(async function testDeactivateExperiment() {
Assert.equal(experiments[0].active, false, "Experiment is not active.");
// We should have a previous experiment in the add-ons manager.
let deferred = Promise.defer();
let addons = await new Promise(resolve => {
AddonManager.getAddonsByTypes(["experiment"], (addons) => {
deferred.resolve(addons);
resolve(addons);
});
});
let addons = await deferred.promise;
Assert.equal(addons.length, 1, "1 experiment add-on known.");
Assert.ok(addons[0].appDisabled, "It is a previous experiment.");
Assert.equal(addons[0].id, "experiment-1", "Add-on ID matches expected.");

View File

@ -68,9 +68,9 @@ function openDetailsView(aId) {
EventUtils.synthesizeMouseAtCenter(item, { clickCount: 1 }, gManagerWindow);
EventUtils.synthesizeMouseAtCenter(item, { clickCount: 2 }, gManagerWindow);
let deferred = Promise.defer();
wait_for_view_load(gManagerWindow, deferred.resolve);
return deferred.promise;
return new Promise(resolve => {
wait_for_view_load(gManagerWindow, resolve);
});
}
add_task(async function initializeState() {
@ -245,16 +245,16 @@ add_task(async function testInstalledDetails() {
el = doc.getElementsByTagName("setting")[0];
let contextMenu = doc.getElementById("addonitem-popup");
let deferred = Promise.defer();
await new Promise(resolve => {
let listener = () => {
contextMenu.removeEventListener("popupshown", listener);
deferred.resolve();
resolve();
};
contextMenu.addEventListener("popupshown", listener);
el = doc.getElementsByClassName("detail-view-container")[0];
EventUtils.synthesizeMouse(el, 4, 4, { }, gManagerWindow);
EventUtils.synthesizeMouse(el, 4, 4, { type: "contextmenu", button: 2 }, gManagerWindow);
await deferred.promise;
});
let menuSep = doc.getElementById("addonitem-menuseparator");
is_element_hidden(menuSep, "Menu separator is hidden.");
contextMenu.hidePopup();
@ -303,9 +303,9 @@ add_task(async function testPreferencesButton() {
let button = doc.getAnonymousElementByAttribute(item, "anonid", "preferences-btn");
EventUtils.synthesizeMouseAtCenter(button, { clickCount: 1 }, gManagerWindow);
let deferred = Promise.defer();
wait_for_view_load(gManagerWindow, deferred.resolve);
await deferred.promise;
await new Promise(resolve => {
wait_for_view_load(gManagerWindow, resolve);
});
is(gOptionsObserver.lastDisplayed, addon.id);
}
@ -333,9 +333,9 @@ add_task(async function testUpdateButton() {
let button = doc.getAnonymousElementByAttribute(item, "anonid", "preferences-btn");
EventUtils.synthesizeMouseAtCenter(button, { clickCount: 1 }, gManagerWindow);
let deferred = Promise.defer();
wait_for_view_load(gManagerWindow, deferred.resolve);
await deferred.promise;
await new Promise(resolve => {
wait_for_view_load(gManagerWindow, resolve);
});
button = doc.getElementById("detail-findUpdates-btn");
Assert.ok(button != null, "Got detail-findUpdates-btn");

View File

@ -44,7 +44,7 @@ ARContext.ServiceRequest = function() {
// Returns promise{window}, resolves with a handle to the compatibility
// check window
function promise_open_compatibility_window(aInactiveAddonIds) {
let deferred = Promise.defer();
return new Promise(resolve => {
// This will reset the longer timeout multiplier to 2 which will give each
// test that calls open_compatibility_window a minimum of 60 seconds to
// complete.
@ -77,17 +77,17 @@ function promise_open_compatibility_window(aInactiveAddonIds) {
dump("Compatibility dialog closed\n");
}, {once: true});
deferred.resolve(win);
resolve(win);
});
});
return deferred.promise;
}
function promise_window_close(aWindow) {
let deferred = Promise.defer();
return new Promise(resolve => {
aWindow.addEventListener("unload", function() {
deferred.resolve(aWindow);
resolve(aWindow);
}, {once: true});
return deferred.promise;
});
}
// Start the compatibility update dialog, but use the mock XHR to respond with

View File

@ -100,7 +100,7 @@ function setQuickMockTimer() {
* is called
*/
function setPromiseMockTimer() {
let waiter = Promise.defer();
return new Promise(resolve => {
let mockTimer = {
callback: null,
delay: null,
@ -114,7 +114,7 @@ function setPromiseMockTimer() {
this.type = aType;
// cancelled timers can be re-used
this.isCancelled = false;
waiter.resolve(this);
resolve(this);
},
cancel() {
do_print("Cancelled mock timer");
@ -123,23 +123,23 @@ function setPromiseMockTimer() {
this.type = null;
this.isCancelled = true;
// If initWithCallback was never called, resolve to let tests check for cancel
waiter.resolve(this);
resolve(this);
}
};
DSContext.MakeTimer = () => {
do_print("Creating mock timer");
return mockTimer;
};
return waiter.promise;
});
}
/**
* Return a Promise<null> that resolves after the specified number of milliseconds
*/
function delay(aDelayMS) {
let deferred = Promise.defer();
do_timeout(aDelayMS, () => deferred.resolve(null));
return deferred.promise;
return new Promise(resolve => {
do_timeout(aDelayMS, () => resolve(null));
});
}
function run_test() {
@ -250,10 +250,10 @@ add_task(async function dirty_while_writing() {
let thirdData = "Third data";
let firstCallback_happened = false;
let secondCallback_happened = false;
let writeStarted = Promise.defer();
let writer = await new Promise(resolve => {
function writeCallback(aTester) {
writeStarted.resolve(aTester.waDeferred);
resolve(aTester.waDeferred);
}
setQuickMockTimer();
@ -267,7 +267,7 @@ add_task(async function dirty_while_writing() {
}, do_report_unexpected_exception);
do_print("waiting for writer");
let writer = await writeStarted.promise;
});
do_print("Write started");
// Delay a bit, modify the data and call saveChanges, delay a bit more,
@ -331,10 +331,10 @@ add_task(async function flush_during_write() {
let tester = DeferredSaveTester();
let dataToSave = "Flush during write";
let firstCallback_happened = false;
let writeStarted = Promise.defer();
let writer = await new Promise(resolve => {
function writeCallback(aTester) {
writeStarted.resolve(aTester.waDeferred);
resolve(aTester.waDeferred);
}
setQuickMockTimer();
@ -344,7 +344,7 @@ add_task(async function flush_during_write() {
firstCallback_happened = true;
}, do_report_unexpected_exception);
let writer = await writeStarted.promise;
});
// call flush with the write callback disabled, delay a bit more, complete in-progress write
let flushing = tester.flush(disabled_write_callback);

View File

@ -159,7 +159,7 @@ add_task(async function init() {
"addon4@tests.mozilla.org",
"addon7@tests.mozilla.org",
"theme2@tests.mozilla.org"]);
let deferredUpdateFinished = Promise.defer();
await new Promise(resolve => {
// Set up the initial state
a2.userDisabled = true;
a4.userDisabled = true;
@ -170,13 +170,13 @@ add_task(async function init() {
a4.findUpdates({
onUpdateFinished() {
// Let the updates finish before restarting the manager
deferredUpdateFinished.resolve();
resolve();
}
}, AddonManager.UPDATE_WHEN_PERIODIC_UPDATE);
}
}, AddonManager.UPDATE_WHEN_PERIODIC_UPDATE);
await deferredUpdateFinished.promise;
});
});

Some files were not shown because too many files have changed in this diff Show More