1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 var EXPORTED_SYMBOLS = [
8 "DOMContentLoadedPromise",
14 const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
16 const { TYPE_REPEATING_SLACK } = Ci.nsITimer;
19 * Wait for a single event to be fired on a specific EventListener.
21 * The returned promise is guaranteed to not be called before the
22 * next event tick after the event listener is called, so that all
23 * other event listeners for the element are executed before the
24 * handler is executed. For example:
26 * const promise = new EventPromise(element, "myEvent");
27 * // same event tick here
29 * // next event tick here
31 * @param {EventListener} listener
32 * Object which receives a notification (an object that implements
33 * the Event interface) when an event of the specificed type occurs.
34 * @param {string} type
35 * Case-sensitive string representing the event type to listen for.
36 * @param {boolean?} [false] options.capture
37 * Indicates the event will be despatched to this subject,
38 * before it bubbles down to any EventTarget beneath it in the
40 * @param {boolean?} [false] options.wantsUntrusted
41 * Receive synthetic events despatched by web content.
42 * @param {boolean?} [false] options.mozSystemGroup
43 * Determines whether to add listener to the system group.
45 * @return {Promise.<Event>}
49 function EventPromise(
54 wantsUntrusted: false,
55 mozSystemGroup: false,
58 if (!listener || !("addEventListener" in listener)) {
59 throw new TypeError();
61 if (typeof type != "string") {
62 throw new TypeError();
65 ("capture" in options && typeof options.capture != "boolean") ||
66 ("wantsUntrusted" in options &&
67 typeof options.wantsUntrusted != "boolean") ||
68 ("mozSystemGroup" in options && typeof options.mozSystemGroup != "boolean")
70 throw new TypeError();
75 return new Promise(resolve => {
76 listener.addEventListener(
79 Services.tm.dispatchToMainThread(() => resolve(event));
86 function DOMContentLoadedPromise(window, options = { mozSystemGroup: true }) {
88 window.document.readyState == "complete" ||
89 window.document.readyState == "interactive"
91 return Promise.resolve();
93 return new EventPromise(window, "DOMContentLoaded", options);
97 * Awaits a single IPC message.
99 * @param {nsIMessageSender} target
100 * @param {string} name
104 * @throws {TypeError}
105 * If target is not an nsIMessageSender.
107 function MessagePromise(target, name) {
108 if (!(target instanceof Ci.nsIMessageSender)) {
109 throw new TypeError();
112 return new Promise(resolve => {
113 const onMessage = (...args) => {
114 target.removeMessageListener(name, onMessage);
117 target.addMessageListener(name, onMessage);
122 * Runs a Promise-like function off the main thread until it is resolved
123 * through ``resolve`` or ``rejected`` callbacks. The function is
124 * guaranteed to be run at least once, irregardless of the timeout.
126 * The ``func`` is evaluated every ``interval`` for as long as its
127 * runtime duration does not exceed ``interval``. Evaluations occur
128 * sequentially, meaning that evaluations of ``func`` are queued if
129 * the runtime evaluation duration of ``func`` is greater than ``interval``.
131 * ``func`` is given two arguments, ``resolve`` and ``reject``,
132 * of which one must be called for the evaluation to complete.
133 * Calling ``resolve`` with an argument indicates that the expected
134 * wait condition was met and will return the passed value to the
135 * caller. Conversely, calling ``reject`` will evaluate ``func``
136 * again until the ``timeout`` duration has elapsed or ``func`` throws.
137 * The passed value to ``reject`` will also be returned to the caller
138 * once the wait has expired.
142 * let els = new PollPromise((resolve, reject) => {
143 * let res = document.querySelectorAll("p");
144 * if (res.length > 0) {
145 * resolve(Array.from(res));
149 * }, {timeout: 1000});
151 * @param {Condition} func
152 * Function to run off the main thread.
153 * @param {number=} [timeout] timeout
154 * Desired timeout if wanted. If 0 or less than the runtime evaluation
155 * time of ``func``, ``func`` is guaranteed to run at least once.
156 * Defaults to using no timeout.
157 * @param {number=} [interval=10] interval
158 * Duration between each poll of ``func`` in milliseconds.
159 * Defaults to 10 milliseconds.
161 * @return {Promise.<*>}
162 * Yields the value passed to ``func``'s
163 * ``resolve`` or ``reject`` callbacks.
166 * If ``func`` throws, its error is propagated.
167 * @throws {TypeError}
168 * If `timeout` or `interval`` are not numbers.
169 * @throws {RangeError}
170 * If `timeout` or `interval` are not unsigned integers.
172 function PollPromise(func, { timeout = null, interval = 10 } = {}) {
173 const timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
175 if (typeof func != "function") {
176 throw new TypeError();
178 if (timeout != null && typeof timeout != "number") {
179 throw new TypeError();
181 if (typeof interval != "number") {
182 throw new TypeError();
185 (timeout && (!Number.isInteger(timeout) || timeout < 0)) ||
186 (!Number.isInteger(interval) || interval < 0)
188 throw new RangeError();
191 return new Promise((resolve, reject) => {
194 if (Number.isInteger(timeout)) {
195 start = new Date().getTime();
196 end = start + timeout;
201 .then(resolve, rejected => {
202 if (typeof rejected != "undefined") {
206 // return if there is a timeout and set to 0,
207 // allowing |func| to be evaluated at least once
209 typeof end != "undefined" &&
210 (start == end || new Date().getTime() >= end)
218 // the repeating slack timer waits |interval|
219 // before invoking |evalFn|
222 timer.init(evalFn, interval, TYPE_REPEATING_SLACK);