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/. */
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.
15 * In the general case, this script should be used by importing Promise.jsm:
17 * Components.utils.import("resource://gre/modules/Promise.jsm");
19 * More documentation can be found in the Promise.jsm module.
24 // Obtain an instance of Cu. How this instance is obtained depends on how this
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
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.
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"));
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
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.
120 // Functions registered to be notified when a pending error
121 // is reported as uncaught.
122 _observers: new Set(),
126 * Initialize PendingErrors
129 Services.obs.addObserver(function observe(aSubject, aTopic, aValue) {
130 PendingErrors.report(aValue);
131 }, "promise-finalization-witness");
135 * Register an error as tracked.
137 * @return The unique identifier of the error.
140 let id = "pending-error-" + (this._counter++);
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.
150 // To avoid this situation, we rather extract relevant data from
151 // the error and further normalize it to strings.
160 try { // Defend against non-enumerable values
161 if (error && error instanceof Ci.nsIException) {
162 // nsIException does things a little differently.
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;
171 // All lowercase filename. ;)
172 value.fileName = error.filename;
177 value.lineNumber = error.lineNumber;
181 } else if (typeof error == "object" && error) {
182 for (let k of ["fileName", "stack", "lineNumber"]) {
183 try { // Defend against fallible getters and string conversions
185 value[k] = v ? ("" + v) : null;
193 // |error| is not an Error (or Error-alike). Try to figure out the stack.
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;
200 // Components.stack to the rescue!
201 stack = Components_.stack;
202 // Remove those top frames that refer to Promise.jsm.
204 if (!stack.filename.endsWith("/Promise.jsm")) {
207 stack = stack.caller;
214 stack = stack.caller;
216 value.stack = frames.join("\n");
222 this._map.set(id, value);
227 * Notify all observers that a pending error is now uncaught.
229 * @param id The identifier of the pending error, as returned by
233 let value = this._map.get(id);
235 return; // The error has already been reported
237 this._map.delete(id);
238 for (let obs of this._observers.values()) {
244 * Mark all pending errors are uncaught, notify the observers.
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())) {
255 * Stop tracking an error, as this error has been caught,
259 this._map.delete(id);
263 * Add an observer notified when an error is reported as uncaught.
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.
270 addObserver(observer) {
271 this._observers.add(observer);
275 * Remove an observer added with addObserver
277 removeObserver(observer) {
278 this._observers.delete(observer);
282 * Remove all the observers added with addObserver
284 removeAllObservers() {
285 this._observers.clear();
289 // Initialize the warn-upon-finalization mechanism if and only if Cu is defined.
290 // Otherwise, FinalizationWitnessService won't be defined (see above).
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");
312 let message = details.message;
314 message += "\nFull Stack: " + details.stack;
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,
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"];
338 * The Promise constructor. Creates a new promise given an executor callback.
339 * The executor callback is called with the resolve and reject handlers.
342 * The callback that will be called with resolve and reject.
344 this.Promise = function Promise(aExecutor) {
345 if (typeof(aExecutor) != "function") {
346 throw new TypeError("Promise constructor must be called with an executor.");
350 * Object holding all of our internal values we associate with the promise.
352 Object.defineProperty(this, N_INTERNALS, { value: {
354 * Internal status of the promise. This can be equal to STATUS_PENDING,
355 * STATUS_RESOLVED, or STATUS_REJECTED.
357 status: STATUS_PENDING,
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.
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.
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".
386 let resolve = PromiseWalker.completePromise
387 .bind(PromiseWalker, this, STATUS_RESOLVED);
388 let reject = PromiseWalker.completePromise
389 .bind(PromiseWalker, this, STATUS_REJECTED);
392 aExecutor(resolve, reject);
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.
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.
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
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.
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;
454 PendingErrors.unregister(id);
457 PromiseWalker.schedulePromise(this);
460 return handler.nextPromise;
464 * Invokes `promise.then` with undefined for the resolve handler and a given
468 * The rejection handler.
470 * @return A new pending promise returned.
472 * @see Promise.prototype.then
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.
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.
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.
501 Promise.resolve = function(aValue) {
502 if (aValue && typeof(aValue) == "function" && aValue.isAsyncFunction) {
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.");
510 if (aValue instanceof Promise) {
514 return new Promise((aResolve) => aResolve(aValue));
518 * Creates a new promise rejected with the specified reason.
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.
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.
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.
551 Promise.all = function(aValues) {
552 if (aValues == null || typeof(aValues[Symbol.iterator]) != "function") {
553 throw new Error("Promise.all() expects an iterable.");
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);
562 resolve(resolutionValues);
566 function checkForCompletion(aValue, aIndex) {
567 resolutionValues[aIndex] = aValue;
568 if (--countdown === 0) {
569 resolve(resolutionValues);
573 for (let i = 0; i < values.length; 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);
581 // Given value is not a promise, forward it as a resolution value.
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.
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.
601 Promise.race = function(aValues) {
602 if (aValues == null || typeof(aValues[Symbol.iterator]) != "function") {
603 throw new Error("Promise.race() expects an iterable.");
606 return new Promise((resolve, reject) => {
607 for (let value of aValues) {
608 Promise.resolve(value).then(resolve, reject);
613 Promise.Debugging = {
615 * Add an observer notified when an error is reported as uncaught.
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.
622 addUncaughtErrorObserver(observer) {
623 PendingErrors.addObserver(observer);
627 * Remove an observer added with addUncaughtErrorObserver
629 * @param {function} An observer registered with
630 * addUncaughtErrorObserver.
632 removeUncaughtErrorObserver(observer) {
633 PendingErrors.removeObserver(observer);
637 * Remove all the observers added with addUncaughtErrorObserver
639 clearUncaughtErrorObservers() {
640 PendingErrors.removeAllObservers();
644 * Force all pending errors to be reported immediately as uncaught.
645 * Note that this may cause some false positives.
647 flushUncaughtErrors() {
648 PendingErrors.flush();
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.
658 module.exports = Promise;
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.
671 this.PromiseWalker = {
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.
680 * Called when a promise needs to change state to be resolved or rejected.
683 * Promise that needs to change state. If this is already resolved or
684 * rejected, this method has no effect.
686 * New desired status, either STATUS_RESOLVED or STATUS_REJECTED.
688 * Associated resolution value or rejection reason.
690 completePromise(aPromise, aStatus, aValue) {
691 // Do nothing if the promise is already resolved or rejected.
692 if (aPromise[N_INTERNALS].status != STATUS_PENDING) {
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));
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);
715 FinalizationWitnessService.make("promise-finalization-witness", id);
716 aPromise[N_INTERNALS].witness = [id, witness];
721 * Sets up the PromiseWalker loop to start on the next tick of the event loop
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.
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.
738 // If Cu is defined, this file is loaded on the main thread. Otherwise, it
739 // is loaded on the worker thread.
741 let stack = Components_ ? Components_.stack : null;
743 DOMPromise.resolve().then(() => {
744 Cu.callFunctionWithAsyncStack(this.walkerLoop.bind(this), stack,
748 DOMPromise.resolve().then(() => this.walkerLoop());
751 setImmediate(this.walkerLoop);
756 * Schedules the resolution or rejection handlers registered on the provided
757 * promise for processing.
760 * Resolved or rejected promise whose handlers should be processed. It
761 * is expected that this promise has at least one handler to process.
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);
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();
777 * Indicates whether the walker loop is currently scheduled for execution on
778 * the next tick of the event loop.
780 walkerLoopScheduled: false,
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.
787 * This function is called with "this" bound to the PromiseWalker object.
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();
803 this.walkerLoopScheduled = false;
806 // Process all the known handlers eagerly.
807 while (this.handlers.length > 0) {
808 this.handlers.shift().process();
813 // Bind the function to the singleton once.
814 PromiseWalker.walkerLoop = PromiseWalker.walkerLoop.bind(PromiseWalker);
819 * Returned by "Promise.defer" to provide a new promise along with methods to
822 function Deferred() {
823 this.promise = new Promise((aResolve, aReject) => {
824 this.resolve = aResolve;
825 this.reject = aReject;
830 Deferred.prototype = {
832 * A newly created promise, initially in the pending state.
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.
841 * This function is bound to its associated promise when "Promise.defer" is
842 * called, and can be called with any value of "this".
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.
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.
857 * Rejects the associated promise with the specified reason. If the promise
858 * has already been resolved or rejected, this method does nothing.
860 * This function is bound to its associated promise when "Promise.defer" is
861 * called, and can be called with any value of "this".
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.
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.
879 * Handler registered on a promise by the "then" function.
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 = {
890 * Promise on which the "then" method was called.
895 * Unmodified resolution handler provided to the "then" method.
900 * Unmodified rejection handler provided to the "then" method.
905 * New promise that will be returned by the "then" method.
910 * Called after thisPromise is resolved or rejected, invokes the appropriate
911 * callback and propagates the result to nextPromise.
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;
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);
926 } else if (typeof(this.onReject) == "function") {
927 nextValue = this.onReject.call(undefined, nextValue);
928 nextStatus = STATUS_RESOLVED;
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") +
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");
954 // Additionally, reject the next promise.
955 nextStatus = STATUS_REJECTED;
959 // Propagate the newly determined state to the next promise.
960 PromiseWalker.completePromise(this.nextPromise, nextStatus, nextValue);