Bug 1518618 - Add custom classes to the selectors for matches, attributes and pseudoc...
[gecko.git] / toolkit / modules / Promise-backend.js
blob18607542d67315a93d1c699e533e512a68b4aa9b
1 /* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
2 /* vim: set ts=2 et sw=2 tw=80 filetype=javascript: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 "use strict";
9 /**
10  * This implementation file is imported by the Promise.jsm module, and as a
11  * special case by the debugger server.  To support chrome debugging, the
12  * debugger server needs to have all its code in one global, so it must use
13  * loadSubScript directly.
14  *
15  * In the general case, this script should be used by importing Promise.jsm:
16  *
17  * Components.utils.import("resource://gre/modules/Promise.jsm");
18  *
19  * More documentation can be found in the Promise.jsm module.
20  */
22 // Globals
24 // Obtain an instance of Cu. How this instance is obtained depends on how this
25 // file is loaded.
27 // This file can be loaded in three different ways:
28 // 1. As a CommonJS module, by Loader.jsm, on the main thread.
29 // 2. As a CommonJS module, by worker-loader.js, on a worker thread.
30 // 3. As a subscript, by Promise.jsm, on the main thread.
32 // If require is defined, the file is loaded as a CommonJS module. Components
33 // will not be defined in that case, but we can obtain an instance of Cu from
34 // the chrome module. Otherwise, this file is loaded as a subscript, and we can
35 // obtain an instance of Cu from Components directly.
37 // If the file is loaded as a CommonJS module on a worker thread, the instance
38 // of Cu obtained from the chrome module will be null. The reason for this is
39 // that Components is not defined in worker threads, so no instance of Cu can
40 // be obtained.
42 // As this can be loaded in several ways, allow require and module to be defined.
43 /* global module:false require:false */
44 // This is allowed in workers.
45 /* global setImmediate:false */
47 /* eslint-disable mozilla/no-define-cc-etc */
48 /* eslint-disable mozilla/use-cc-etc */
49 var Cu = this.require ? require("chrome").Cu : Components.utils;
50 var Cc = this.require ? require("chrome").Cc : Components.classes;
51 var Ci = this.require ? require("chrome").Ci : Components.interfaces;
52 /* eslint-enable mozilla/use-cc-etc */
53 /* eslint-enable mozilla/no-define-cc-etc */
54 // If we can access Components, then we use it to capture an async
55 // parent stack trace; see scheduleWalkerLoop.  However, as it might
56 // not be available (see above), users of this must check it first.
57 var Components_ = this.require ? require("chrome").components : Components;
59 // If Cu is defined, use it to lazily define the FinalizationWitnessService.
60 if (Cu) {
61   // If we're in a devtools module environment, ChromeUtils won't exist.
62   /* eslint "mozilla/use-chromeutils-import": ["error", {allowCu: true}] */
63   Cu.import("resource://gre/modules/Services.jsm", this);
64   Cu.import("resource://gre/modules/XPCOMUtils.jsm", this);
66   XPCOMUtils.defineLazyServiceGetter(this, "FinalizationWitnessService",
67                                      "@mozilla.org/toolkit/finalizationwitness;1",
68                                      "nsIFinalizationWitnessService");
71 const STATUS_PENDING = 0;
72 const STATUS_RESOLVED = 1;
73 const STATUS_REJECTED = 2;
75 // This N_INTERNALS name allow internal properties of the Promise to be
76 // accessed only by this module, while still being visible on the object
77 // manually when using a debugger.  This doesn't strictly guarantee that the
78 // properties are inaccessible by other code, but provide enough protection to
79 // avoid using them by mistake.
80 const salt = Math.floor(Math.random() * 100);
81 const N_INTERNALS = "{private:internals:" + salt + "}";
83 // We use DOM Promise for scheduling the walker loop.
84 const DOMPromise = Cu ? Promise : null;
86 // Warn-upon-finalization mechanism
88 // One of the difficult problems with promises is locating uncaught
89 // rejections. We adopt the following strategy: if a promise is rejected
90 // at the time of its garbage-collection *and* if the promise is at the
91 // end of a promise chain (i.e. |thatPromise.then| has never been
92 // called), then we print a warning.
94 //  let deferred = Promise.defer();
95 //  let p = deferred.promise.then();
96 //  deferred.reject(new Error("I am un uncaught error"));
97 //  deferred = null;
98 //  p = null;
100 // In this snippet, since |deferred.promise| is not the last in the
101 // chain, no error will be reported for that promise. However, since
102 // |p| is the last promise in the chain, the error will be reported
103 // for |p|.
105 // Note that this may, in some cases, cause an error to be reported more
106 // than once. For instance, consider:
108 //   let deferred = Promise.defer();
109 //   let p1 = deferred.promise.then();
110 //   let p2 = deferred.promise.then();
111 //   deferred.reject(new Error("I am an uncaught error"));
112 //   p1 = p2 = deferred = null;
114 // In this snippet, the error is reported both by p1 and by p2.
117 var PendingErrors = {
118   // An internal counter, used to generate unique id.
119   _counter: 0,
120   // Functions registered to be notified when a pending error
121   // is reported as uncaught.
122   _observers: new Set(),
123   _map: new Map(),
125   /**
126    * Initialize PendingErrors
127    */
128   init() {
129     Services.obs.addObserver(function observe(aSubject, aTopic, aValue) {
130       PendingErrors.report(aValue);
131     }, "promise-finalization-witness");
132   },
134   /**
135    * Register an error as tracked.
136    *
137    * @return The unique identifier of the error.
138    */
139   register(error) {
140     let id = "pending-error-" + (this._counter++);
141     //
142     // At this stage, ideally, we would like to store the error itself
143     // and delay any treatment until we are certain that we will need
144     // to report that error. However, in the (unlikely but possible)
145     // case the error holds a reference to the promise itself, doing so
146     // would prevent the promise from being garbabe-collected, which
147     // would both cause a memory leak and ensure that we cannot report
148     // the uncaught error.
149     //
150     // To avoid this situation, we rather extract relevant data from
151     // the error and further normalize it to strings.
152     //
153     let value = {
154       date: new Date(),
155       message: "" + error,
156       fileName: null,
157       stack: null,
158       lineNumber: null,
159     };
160     try { // Defend against non-enumerable values
161       if (error && error instanceof Ci.nsIException) {
162         // nsIException does things a little differently.
163         try {
164           // For starters |.toString()| does not only contain the message, but
165           // also the top stack frame, and we don't really want that.
166           value.message = error.message;
167         } catch (ex) {
168           // Ignore field
169         }
170         try {
171           // All lowercase filename. ;)
172           value.fileName = error.filename;
173         } catch (ex) {
174           // Ignore field
175         }
176         try {
177           value.lineNumber = error.lineNumber;
178         } catch (ex) {
179           // Ignore field
180         }
181       } else if (typeof error == "object" && error) {
182         for (let k of ["fileName", "stack", "lineNumber"]) {
183           try { // Defend against fallible getters and string conversions
184             let v = error[k];
185             value[k] = v ? ("" + v) : null;
186           } catch (ex) {
187             // Ignore field
188           }
189         }
190       }
192       if (!value.stack) {
193         // |error| is not an Error (or Error-alike). Try to figure out the stack.
194         let stack = null;
195         if (error && error.location &&
196             error.location instanceof Ci.nsIStackFrame) {
197           // nsIException has full stack frames in the |.location| member.
198           stack = error.location;
199         } else {
200           // Components.stack to the rescue!
201           stack = Components_.stack;
202           // Remove those top frames that refer to Promise.jsm.
203           while (stack) {
204             if (!stack.filename.endsWith("/Promise.jsm")) {
205               break;
206             }
207             stack = stack.caller;
208           }
209         }
210         if (stack) {
211           let frames = [];
212           while (stack) {
213             frames.push(stack);
214             stack = stack.caller;
215           }
216           value.stack = frames.join("\n");
217         }
218       }
219     } catch (ex) {
220       // Ignore value
221     }
222     this._map.set(id, value);
223     return id;
224   },
226   /**
227    * Notify all observers that a pending error is now uncaught.
228    *
229    * @param id The identifier of the pending error, as returned by
230    * |register|.
231    */
232   report(id) {
233     let value = this._map.get(id);
234     if (!value) {
235       return; // The error has already been reported
236     }
237     this._map.delete(id);
238     for (let obs of this._observers.values()) {
239       obs(value);
240     }
241   },
243   /**
244    * Mark all pending errors are uncaught, notify the observers.
245    */
246   flush() {
247     // Since we are going to modify the map while walking it,
248     // let's copying the keys first.
249     for (let key of Array.from(this._map.keys())) {
250       this.report(key);
251     }
252   },
254   /**
255    * Stop tracking an error, as this error has been caught,
256    * eventually.
257    */
258   unregister(id) {
259     this._map.delete(id);
260   },
262   /**
263    * Add an observer notified when an error is reported as uncaught.
264    *
265    * @param {function} observer A function notified when an error is
266    * reported as uncaught. Its arguments are
267    *   {message, date, fileName, stack, lineNumber}
268    * All arguments are optional.
269    */
270   addObserver(observer) {
271     this._observers.add(observer);
272   },
274   /**
275    * Remove an observer added with addObserver
276    */
277   removeObserver(observer) {
278     this._observers.delete(observer);
279   },
281   /**
282    * Remove all the observers added with addObserver
283    */
284   removeAllObservers() {
285     this._observers.clear();
286   },
289 // Initialize the warn-upon-finalization mechanism if and only if Cu is defined.
290 // Otherwise, FinalizationWitnessService won't be defined (see above).
291 if (Cu) {
292   PendingErrors.init();
295 // Default mechanism for displaying errors
296 PendingErrors.addObserver(function(details) {
297   const generalDescription = "A promise chain failed to handle a rejection." +
298     " Did you forget to '.catch', or did you forget to 'return'?\nSee" +
299     " https://developer.mozilla.org/Mozilla/JavaScript_code_modules/Promise.jsm/Promise\n\n";
301   let error = Cc["@mozilla.org/scripterror;1"].createInstance(Ci.nsIScriptError);
302   if (!error || !Services.console) {
303     // Too late during shutdown to use the nsIConsole
304     dump("*************************\n");
305     dump(generalDescription);
306     dump("On: " + details.date + "\n");
307     dump("Full message: " + details.message + "\n");
308     dump("Full stack: " + (details.stack || "not available") + "\n");
309     dump("*************************\n");
310     return;
311   }
312   let message = details.message;
313   if (details.stack) {
314     message += "\nFull Stack: " + details.stack;
315   }
316   error.init(
317              /* message*/ generalDescription +
318              "Date: " + details.date + "\nFull Message: " + message,
319              /* sourceName*/ details.fileName,
320              /* sourceLine*/ details.lineNumber ? ("" + details.lineNumber) : 0,
321              /* lineNumber*/ details.lineNumber || 0,
322              /* columnNumber*/ 0,
323              /* flags*/ Ci.nsIScriptError.errorFlag,
324              /* category*/ "chrome javascript");
325   Services.console.logMessage(error);
329 // Additional warnings for developers
331 // The following error types are considered programmer errors, which should be
332 // reported (possibly redundantly) so as to let programmers fix their code.
333 const ERRORS_TO_REPORT = ["EvalError", "RangeError", "ReferenceError", "TypeError"];
335 // Promise
338  * The Promise constructor. Creates a new promise given an executor callback.
339  * The executor callback is called with the resolve and reject handlers.
341  * @param aExecutor
342  *        The callback that will be called with resolve and reject.
343  */
344 this.Promise = function Promise(aExecutor) {
345   if (typeof(aExecutor) != "function") {
346     throw new TypeError("Promise constructor must be called with an executor.");
347   }
349   /*
350    * Object holding all of our internal values we associate with the promise.
351    */
352   Object.defineProperty(this, N_INTERNALS, { value: {
353     /*
354      * Internal status of the promise.  This can be equal to STATUS_PENDING,
355      * STATUS_RESOLVED, or STATUS_REJECTED.
356      */
357     status: STATUS_PENDING,
359     /*
360      * When the status property is STATUS_RESOLVED, this contains the final
361      * resolution value, that cannot be a promise, because resolving with a
362      * promise will cause its state to be eventually propagated instead.  When the
363      * status property is STATUS_REJECTED, this contains the final rejection
364      * reason, that could be a promise, even if this is uncommon.
365      */
366     value: undefined,
368     /*
369      * Array of Handler objects registered by the "then" method, and not processed
370      * yet.  Handlers are removed when the promise is resolved or rejected.
371      */
372     handlers: [],
374     /**
375      * When the status property is STATUS_REJECTED and until there is
376      * a rejection callback, this contains an array
377      * - {string} id An id for use with |PendingErrors|;
378      * - {FinalizationWitness} witness A witness broadcasting |id| on
379      *   notification "promise-finalization-witness".
380      */
381     witness: undefined,
382   }});
384   Object.seal(this);
386   let resolve = PromiseWalker.completePromise
387                              .bind(PromiseWalker, this, STATUS_RESOLVED);
388   let reject = PromiseWalker.completePromise
389                             .bind(PromiseWalker, this, STATUS_REJECTED);
391   try {
392     aExecutor(resolve, reject);
393   } catch (ex) {
394     reject(ex);
395   }
399  * Calls one of the provided functions as soon as this promise is either
400  * resolved or rejected.  A new promise is returned, whose state evolves
401  * depending on this promise and the provided callback functions.
403  * The appropriate callback is always invoked after this method returns, even
404  * if this promise is already resolved or rejected.  You can also call the
405  * "then" method multiple times on the same promise, and the callbacks will be
406  * invoked in the same order as they were registered.
408  * @param aOnResolve
409  *        If the promise is resolved, this function is invoked with the
410  *        resolution value of the promise as its only argument, and the
411  *        outcome of the function determines the state of the new promise
412  *        returned by the "then" method.  In case this parameter is not a
413  *        function (usually "null"), the new promise returned by the "then"
414  *        method is resolved with the same value as the original promise.
416  * @param aOnReject
417  *        If the promise is rejected, this function is invoked with the
418  *        rejection reason of the promise as its only argument, and the
419  *        outcome of the function determines the state of the new promise
420  *        returned by the "then" method.  In case this parameter is not a
421  *        function (usually left "undefined"), the new promise returned by the
422  *        "then" method is rejected with the same reason as the original
423  *        promise.
425  * @return A new promise that is initially pending, then assumes a state that
426  *         depends on the outcome of the invoked callback function:
427  *          - If the callback returns a value that is not a promise, including
428  *            "undefined", the new promise is resolved with this resolution
429  *            value, even if the original promise was rejected.
430  *          - If the callback throws an exception, the new promise is rejected
431  *            with the exception as the rejection reason, even if the original
432  *            promise was resolved.
433  *          - If the callback returns a promise, the new promise will
434  *            eventually assume the same state as the returned promise.
436  * @note If the aOnResolve callback throws an exception, the aOnReject
437  *       callback is not invoked.  You can register a rejection callback on
438  *       the returned promise instead, to process any exception occurred in
439  *       either of the callbacks registered on this promise.
440  */
441 Promise.prototype.then = function(aOnResolve, aOnReject) {
442   let handler = new Handler(this, aOnResolve, aOnReject);
443   this[N_INTERNALS].handlers.push(handler);
445   // Ensure the handler is scheduled for processing if this promise is already
446   // resolved or rejected.
447   if (this[N_INTERNALS].status != STATUS_PENDING) {
449     // This promise is not the last in the chain anymore. Remove any watchdog.
450     if (this[N_INTERNALS].witness != null) {
451       let [id, witness] = this[N_INTERNALS].witness;
452       this[N_INTERNALS].witness = null;
453       witness.forget();
454       PendingErrors.unregister(id);
455     }
457     PromiseWalker.schedulePromise(this);
458   }
460   return handler.nextPromise;
464  * Invokes `promise.then` with undefined for the resolve handler and a given
465  * reject handler.
467  * @param aOnReject
468  *        The rejection handler.
470  * @return A new pending promise returned.
472  * @see Promise.prototype.then
473  */
474 Promise.prototype.catch = function(aOnReject) {
475   return this.then(undefined, aOnReject);
479  * Creates a new pending promise and provides methods to resolve or reject it.
481  * @return A new object, containing the new promise in the "promise" property,
482  *         and the methods to change its state in the "resolve" and "reject"
483  *         properties.  See the Deferred documentation for details.
484  */
485 Promise.defer = function() {
486   return new Deferred();
490  * Creates a new promise resolved with the specified value, or propagates the
491  * state of an existing promise.
493  * @param aValue
494  *        If this value is not a promise, including "undefined", it becomes
495  *        the resolution value of the returned promise.  If this value is a
496  *        promise, then the returned promise will eventually assume the same
497  *        state as the provided promise.
499  * @return A promise that can be pending, resolved, or rejected.
500  */
501 Promise.resolve = function(aValue) {
502   if (aValue && typeof(aValue) == "function" && aValue.isAsyncFunction) {
503     throw new TypeError(
504       "Cannot resolve a promise with an async function. " +
505       "You should either invoke the async function first " +
506       "or use 'Task.spawn' instead of 'Task.async' to start " +
507       "the Task and return its promise.");
508   }
510   if (aValue instanceof Promise) {
511     return aValue;
512   }
514   return new Promise((aResolve) => aResolve(aValue));
518  * Creates a new promise rejected with the specified reason.
520  * @param aReason
521  *        The rejection reason for the returned promise.  Although the reason
522  *        can be "undefined", it is generally an Error object, like in
523  *        exception handling.
525  * @return A rejected promise.
527  * @note The aReason argument should not be a promise.  Using a rejected
528  *       promise for the value of aReason would make the rejection reason
529  *       equal to the rejected promise itself, and not its rejection reason.
530  */
531 Promise.reject = function(aReason) {
532   return new Promise((_, aReject) => aReject(aReason));
536  * Returns a promise that is resolved or rejected when all values are
537  * resolved or any is rejected.
539  * @param aValues
540  *        Iterable of promises that may be pending, resolved, or rejected. When
541  *        all are resolved or any is rejected, the returned promise will be
542  *        resolved or rejected as well.
544  * @return A new promise that is fulfilled when all values are resolved or
545  *         that is rejected when any of the values are rejected. Its
546  *         resolution value will be an array of all resolved values in the
547  *         given order, or undefined if aValues is an empty array. The reject
548  *         reason will be forwarded from the first promise in the list of
549  *         given promises to be rejected.
550  */
551 Promise.all = function(aValues) {
552   if (aValues == null || typeof(aValues[Symbol.iterator]) != "function") {
553     throw new Error("Promise.all() expects an iterable.");
554   }
556   return new Promise((resolve, reject) => {
557     let values = Array.isArray(aValues) ? aValues : [...aValues];
558     let countdown = values.length;
559     let resolutionValues = new Array(countdown);
561     if (!countdown) {
562       resolve(resolutionValues);
563       return;
564     }
566     function checkForCompletion(aValue, aIndex) {
567       resolutionValues[aIndex] = aValue;
568       if (--countdown === 0) {
569         resolve(resolutionValues);
570       }
571     }
573     for (let i = 0; i < values.length; i++) {
574       let index = i;
575       let value = values[i];
576       let resolver = val => checkForCompletion(val, index);
578       if (value && typeof(value.then) == "function") {
579         value.then(resolver, reject);
580       } else {
581         // Given value is not a promise, forward it as a resolution value.
582         resolver(value);
583       }
584     }
585   });
589  * Returns a promise that is resolved or rejected when the first value is
590  * resolved or rejected, taking on the value or reason of that promise.
592  * @param aValues
593  *        Iterable of values or promises that may be pending, resolved, or
594  *        rejected. When any is resolved or rejected, the returned promise will
595  *        be resolved or rejected as to the given value or reason.
597  * @return A new promise that is fulfilled when any values are resolved or
598  *         rejected. Its resolution value will be forwarded from the resolution
599  *         value or rejection reason.
600  */
601 Promise.race = function(aValues) {
602   if (aValues == null || typeof(aValues[Symbol.iterator]) != "function") {
603     throw new Error("Promise.race() expects an iterable.");
604   }
606   return new Promise((resolve, reject) => {
607     for (let value of aValues) {
608       Promise.resolve(value).then(resolve, reject);
609     }
610   });
613 Promise.Debugging = {
614   /**
615    * Add an observer notified when an error is reported as uncaught.
616    *
617    * @param {function} observer A function notified when an error is
618    * reported as uncaught. Its arguments are
619    *   {message, date, fileName, stack, lineNumber}
620    * All arguments are optional.
621    */
622   addUncaughtErrorObserver(observer) {
623     PendingErrors.addObserver(observer);
624   },
626   /**
627    * Remove an observer added with addUncaughtErrorObserver
628    *
629    * @param {function} An observer registered with
630    * addUncaughtErrorObserver.
631    */
632   removeUncaughtErrorObserver(observer) {
633     PendingErrors.removeObserver(observer);
634   },
636   /**
637    * Remove all the observers added with addUncaughtErrorObserver
638    */
639   clearUncaughtErrorObservers() {
640     PendingErrors.removeAllObservers();
641   },
643   /**
644    * Force all pending errors to be reported immediately as uncaught.
645    * Note that this may cause some false positives.
646    */
647   flushUncaughtErrors() {
648     PendingErrors.flush();
649   },
651 Object.freeze(Promise.Debugging);
653 Object.freeze(Promise);
655 // If module is defined, this file is loaded as a CommonJS module. Make sure
656 // Promise is exported in that case.
657 if (this.module) {
658   module.exports = Promise;
661 // PromiseWalker
664  * This singleton object invokes the handlers registered on resolved and
665  * rejected promises, ensuring that processing is not recursive and is done in
666  * the same order as registration occurred on each promise.
668  * There is no guarantee on the order of execution of handlers registered on
669  * different promises.
670  */
671 this.PromiseWalker = {
672   /**
673    * Singleton array of all the unprocessed handlers currently registered on
674    * resolved or rejected promises.  Handlers are removed from the array as soon
675    * as they are processed.
676    */
677   handlers: [],
679   /**
680    * Called when a promise needs to change state to be resolved or rejected.
681    *
682    * @param aPromise
683    *        Promise that needs to change state.  If this is already resolved or
684    *        rejected, this method has no effect.
685    * @param aStatus
686    *        New desired status, either STATUS_RESOLVED or STATUS_REJECTED.
687    * @param aValue
688    *        Associated resolution value or rejection reason.
689    */
690   completePromise(aPromise, aStatus, aValue) {
691     // Do nothing if the promise is already resolved or rejected.
692     if (aPromise[N_INTERNALS].status != STATUS_PENDING) {
693       return;
694     }
696     // Resolving with another promise will cause this promise to eventually
697     // assume the state of the provided promise.
698     if (aStatus == STATUS_RESOLVED && aValue &&
699         typeof(aValue.then) == "function") {
700       aValue.then(this.completePromise.bind(this, aPromise, STATUS_RESOLVED),
701                   this.completePromise.bind(this, aPromise, STATUS_REJECTED));
702       return;
703     }
705     // Change the promise status and schedule our handlers for processing.
706     aPromise[N_INTERNALS].status = aStatus;
707     aPromise[N_INTERNALS].value = aValue;
708     if (aPromise[N_INTERNALS].handlers.length > 0) {
709       this.schedulePromise(aPromise);
710     } else if (Cu && aStatus == STATUS_REJECTED) {
711       // This is a rejection and the promise is the last in the chain.
712       // For the time being we therefore have an uncaught error.
713       let id = PendingErrors.register(aValue);
714       let witness =
715           FinalizationWitnessService.make("promise-finalization-witness", id);
716       aPromise[N_INTERNALS].witness = [id, witness];
717     }
718   },
720   /**
721    * Sets up the PromiseWalker loop to start on the next tick of the event loop
722    */
723   scheduleWalkerLoop() {
724     this.walkerLoopScheduled = true;
726     // If this file is loaded on a worker thread, DOMPromise will not behave as
727     // expected: because native promises are not aware of nested event loops
728     // created by the debugger, their respective handlers will not be called
729     // until after leaving the nested event loop. The debugger server relies
730     // heavily on the use promises, so this could cause the debugger to hang.
731     //
732     // To work around this problem, any use of native promises in the debugger
733     // server should be avoided when it is running on a worker thread. Because
734     // it is still necessary to be able to schedule runnables on the event
735     // queue, the worker loader defines the function setImmediate as a
736     // per-module global for this purpose.
737     //
738     // If Cu is defined, this file is loaded on the main thread. Otherwise, it
739     // is loaded on the worker thread.
740     if (Cu) {
741       let stack = Components_ ? Components_.stack : null;
742       if (stack) {
743         DOMPromise.resolve().then(() => {
744           Cu.callFunctionWithAsyncStack(this.walkerLoop.bind(this), stack,
745                                         "Promise");
746         });
747       } else {
748         DOMPromise.resolve().then(() => this.walkerLoop());
749       }
750     } else {
751       setImmediate(this.walkerLoop);
752     }
753   },
755   /**
756    * Schedules the resolution or rejection handlers registered on the provided
757    * promise for processing.
758    *
759    * @param aPromise
760    *        Resolved or rejected promise whose handlers should be processed.  It
761    *        is expected that this promise has at least one handler to process.
762    */
763   schedulePromise(aPromise) {
764     // Migrate the handlers from the provided promise to the global list.
765     for (let handler of aPromise[N_INTERNALS].handlers) {
766       this.handlers.push(handler);
767     }
768     aPromise[N_INTERNALS].handlers.length = 0;
770     // Schedule the walker loop on the next tick of the event loop.
771     if (!this.walkerLoopScheduled) {
772       this.scheduleWalkerLoop();
773     }
774   },
776   /**
777    * Indicates whether the walker loop is currently scheduled for execution on
778    * the next tick of the event loop.
779    */
780   walkerLoopScheduled: false,
782   /**
783    * Processes all the known handlers during this tick of the event loop.  This
784    * eager processing is done to avoid unnecessarily exiting and re-entering the
785    * JavaScript context for each handler on a resolved or rejected promise.
786    *
787    * This function is called with "this" bound to the PromiseWalker object.
788    */
789   walkerLoop() {
790     // If there is more than one handler waiting, reschedule the walker loop
791     // immediately.  Otherwise, use walkerLoopScheduled to tell schedulePromise()
792     // to reschedule the loop if it adds more handlers to the queue.  This makes
793     // this walker resilient to the case where one handler does not return, but
794     // starts a nested event loop.  In that case, the newly scheduled walker will
795     // take over.  In the common case, the newly scheduled walker will be invoked
796     // after this one has returned, with no actual handler to process.  This
797     // small overhead is required to make nested event loops work correctly, but
798     // occurs at most once per resolution chain, thus having only a minor
799     // impact on overall performance.
800     if (this.handlers.length > 1) {
801       this.scheduleWalkerLoop();
802     } else {
803       this.walkerLoopScheduled = false;
804     }
806     // Process all the known handlers eagerly.
807     while (this.handlers.length > 0) {
808       this.handlers.shift().process();
809     }
810   },
813 // Bind the function to the singleton once.
814 PromiseWalker.walkerLoop = PromiseWalker.walkerLoop.bind(PromiseWalker);
816 // Deferred
819  * Returned by "Promise.defer" to provide a new promise along with methods to
820  * change its state.
821  */
822 function Deferred() {
823   this.promise = new Promise((aResolve, aReject) => {
824     this.resolve = aResolve;
825     this.reject = aReject;
826   });
827   Object.freeze(this);
830 Deferred.prototype = {
831   /**
832    * A newly created promise, initially in the pending state.
833    */
834   promise: null,
836   /**
837    * Resolves the associated promise with the specified value, or propagates the
838    * state of an existing promise.  If the associated promise has already been
839    * resolved or rejected, this method does nothing.
840    *
841    * This function is bound to its associated promise when "Promise.defer" is
842    * called, and can be called with any value of "this".
843    *
844    * @param aValue
845    *        If this value is not a promise, including "undefined", it becomes
846    *        the resolution value of the associated promise.  If this value is a
847    *        promise, then the associated promise will eventually assume the same
848    *        state as the provided promise.
849    *
850    * @note Calling this method with a pending promise as the aValue argument,
851    *       and then calling it again with another value before the promise is
852    *       resolved or rejected, has unspecified behavior and should be avoided.
853    */
854   resolve: null,
856   /**
857    * Rejects the associated promise with the specified reason.  If the promise
858    * has already been resolved or rejected, this method does nothing.
859    *
860    * This function is bound to its associated promise when "Promise.defer" is
861    * called, and can be called with any value of "this".
862    *
863    * @param aReason
864    *        The rejection reason for the associated promise.  Although the
865    *        reason can be "undefined", it is generally an Error object, like in
866    *        exception handling.
867    *
868    * @note The aReason argument should not generally be a promise.  In fact,
869    *       using a rejected promise for the value of aReason would make the
870    *       rejection reason equal to the rejected promise itself, not to the
871    *       rejection reason of the rejected promise.
872    */
873   reject: null,
876 // Handler
879  * Handler registered on a promise by the "then" function.
880  */
881 function Handler(aThisPromise, aOnResolve, aOnReject) {
882   this.thisPromise = aThisPromise;
883   this.onResolve = aOnResolve;
884   this.onReject = aOnReject;
885   this.nextPromise = new Promise(() => {});
888 Handler.prototype = {
889   /**
890    * Promise on which the "then" method was called.
891    */
892   thisPromise: null,
894   /**
895    * Unmodified resolution handler provided to the "then" method.
896    */
897   onResolve: null,
899   /**
900    * Unmodified rejection handler provided to the "then" method.
901    */
902   onReject: null,
904   /**
905    * New promise that will be returned by the "then" method.
906    */
907   nextPromise: null,
909   /**
910    * Called after thisPromise is resolved or rejected, invokes the appropriate
911    * callback and propagates the result to nextPromise.
912    */
913   process() {
914     // The state of this promise is propagated unless a handler is defined.
915     let nextStatus = this.thisPromise[N_INTERNALS].status;
916     let nextValue = this.thisPromise[N_INTERNALS].value;
918     try {
919       // If a handler is defined for either resolution or rejection, invoke it
920       // to determine the state of the next promise, that will be resolved with
921       // the returned value, that can also be another promise.
922       if (nextStatus == STATUS_RESOLVED) {
923         if (typeof(this.onResolve) == "function") {
924           nextValue = this.onResolve.call(undefined, nextValue);
925         }
926       } else if (typeof(this.onReject) == "function") {
927         nextValue = this.onReject.call(undefined, nextValue);
928         nextStatus = STATUS_RESOLVED;
929       }
930     } catch (ex) {
932       // An exception has occurred in the handler.
934       if (ex && typeof ex == "object" && "name" in ex &&
935           ERRORS_TO_REPORT.includes(ex.name)) {
937         // We suspect that the exception is a programmer error, so we now
938         // display it using dump().  Note that we do not use Cu.reportError as
939         // we assume that this is a programming error, so we do not want end
940         // users to see it. Also, if the programmer handles errors correctly,
941         // they will either treat the error or log them somewhere.
943         dump("*************************\n");
944         dump("A coding exception was thrown in a Promise " +
945              ((nextStatus == STATUS_RESOLVED) ? "resolution" : "rejection") +
946              " callback.\n");
947         dump("See https://developer.mozilla.org/Mozilla/JavaScript_code_modules/Promise.jsm/Promise\n\n");
948         dump("Full message: " + ex + "\n");
949         dump("Full stack: " + (("stack" in ex) ? ex.stack : "not available") + "\n");
950         dump("*************************\n");
952       }
954       // Additionally, reject the next promise.
955       nextStatus = STATUS_REJECTED;
956       nextValue = ex;
957     }
959     // Propagate the newly determined state to the next promise.
960     PromiseWalker.completePromise(this.nextPromise, nextStatus, nextValue);
961   },