michael@0: /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ michael@0: /* vim: set ts=2 et sw=2 tw=80 filetype=javascript: */ michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: "use strict"; michael@0: michael@0: /** michael@0: * This implementation file is imported by the Promise.jsm module, and as a michael@0: * special case by the debugger server. To support chrome debugging, the michael@0: * debugger server needs to have all its code in one global, so it must use michael@0: * loadSubScript directly. michael@0: * michael@0: * In the general case, this script should be used by importing Promise.jsm: michael@0: * michael@0: * Components.utils.import("resource://gre/modules/Promise.jsm"); michael@0: * michael@0: * More documentation can be found in the Promise.jsm module. michael@0: */ michael@0: michael@0: //////////////////////////////////////////////////////////////////////////////// michael@0: //// Globals michael@0: michael@0: Cu.import("resource://gre/modules/Services.jsm"); michael@0: Cu.import("resource://gre/modules/XPCOMUtils.jsm"); michael@0: michael@0: const STATUS_PENDING = 0; michael@0: const STATUS_RESOLVED = 1; michael@0: const STATUS_REJECTED = 2; michael@0: michael@0: // These "private names" allow some properties of the Promise object to be michael@0: // accessed only by this module, while still being visible on the object michael@0: // manually when using a debugger. They don't strictly guarantee that the michael@0: // properties are inaccessible by other code, but provide enough protection to michael@0: // avoid using them by mistake. michael@0: const salt = Math.floor(Math.random() * 100); michael@0: const Name = (n) => "{private:" + n + ":" + salt + "}"; michael@0: const N_STATUS = Name("status"); michael@0: const N_VALUE = Name("value"); michael@0: const N_HANDLERS = Name("handlers"); michael@0: const N_WITNESS = Name("witness"); michael@0: michael@0: michael@0: /////// Warn-upon-finalization mechanism michael@0: // michael@0: // One of the difficult problems with promises is locating uncaught michael@0: // rejections. We adopt the following strategy: if a promise is rejected michael@0: // at the time of its garbage-collection *and* if the promise is at the michael@0: // end of a promise chain (i.e. |thatPromise.then| has never been michael@0: // called), then we print a warning. michael@0: // michael@0: // let deferred = Promise.defer(); michael@0: // let p = deferred.promise.then(); michael@0: // deferred.reject(new Error("I am un uncaught error")); michael@0: // deferred = null; michael@0: // p = null; michael@0: // michael@0: // In this snippet, since |deferred.promise| is not the last in the michael@0: // chain, no error will be reported for that promise. However, since michael@0: // |p| is the last promise in the chain, the error will be reported michael@0: // for |p|. michael@0: // michael@0: // Note that this may, in some cases, cause an error to be reported more michael@0: // than once. For instance, consider: michael@0: // michael@0: // let deferred = Promise.defer(); michael@0: // let p1 = deferred.promise.then(); michael@0: // let p2 = deferred.promise.then(); michael@0: // deferred.reject(new Error("I am an uncaught error")); michael@0: // p1 = p2 = deferred = null; michael@0: // michael@0: // In this snippet, the error is reported both by p1 and by p2. michael@0: // michael@0: michael@0: XPCOMUtils.defineLazyServiceGetter(this, "FinalizationWitnessService", michael@0: "@mozilla.org/toolkit/finalizationwitness;1", michael@0: "nsIFinalizationWitnessService"); michael@0: michael@0: let PendingErrors = { michael@0: // An internal counter, used to generate unique id. michael@0: _counter: 0, michael@0: // Functions registered to be notified when a pending error michael@0: // is reported as uncaught. michael@0: _observers: new Set(), michael@0: _map: new Map(), michael@0: michael@0: /** michael@0: * Initialize PendingErrors michael@0: */ michael@0: init: function() { michael@0: Services.obs.addObserver(function observe(aSubject, aTopic, aValue) { michael@0: PendingErrors.report(aValue); michael@0: }, "promise-finalization-witness", false); michael@0: }, michael@0: michael@0: /** michael@0: * Register an error as tracked. michael@0: * michael@0: * @return The unique identifier of the error. michael@0: */ michael@0: register: function(error) { michael@0: let id = "pending-error-" + (this._counter++); michael@0: // michael@0: // At this stage, ideally, we would like to store the error itself michael@0: // and delay any treatment until we are certain that we will need michael@0: // to report that error. However, in the (unlikely but possible) michael@0: // case the error holds a reference to the promise itself, doing so michael@0: // would prevent the promise from being garbabe-collected, which michael@0: // would both cause a memory leak and ensure that we cannot report michael@0: // the uncaught error. michael@0: // michael@0: // To avoid this situation, we rather extract relevant data from michael@0: // the error and further normalize it to strings. michael@0: // michael@0: let value = { michael@0: date: new Date(), michael@0: message: "" + error, michael@0: fileName: null, michael@0: stack: null, michael@0: lineNumber: null michael@0: }; michael@0: try { // Defend against non-enumerable values michael@0: if (error && error instanceof Ci.nsIException) { michael@0: // nsIException does things a little differently. michael@0: try { michael@0: // For starters |.toString()| does not only contain the message, but michael@0: // also the top stack frame, and we don't really want that. michael@0: value.message = error.message; michael@0: } catch (ex) { michael@0: // Ignore field michael@0: } michael@0: try { michael@0: // All lowercase filename. ;) michael@0: value.fileName = error.filename; michael@0: } catch (ex) { michael@0: // Ignore field michael@0: } michael@0: try { michael@0: value.lineNumber = error.lineNumber; michael@0: } catch (ex) { michael@0: // Ignore field michael@0: } michael@0: } else if (typeof error == "object" && error) { michael@0: for (let k of ["fileName", "stack", "lineNumber"]) { michael@0: try { // Defend against fallible getters and string conversions michael@0: let v = error[k]; michael@0: value[k] = v ? ("" + v) : null; michael@0: } catch (ex) { michael@0: // Ignore field michael@0: } michael@0: } michael@0: } michael@0: michael@0: if (!value.stack) { michael@0: // |error| is not an Error (or Error-alike). Try to figure out the stack. michael@0: let stack = null; michael@0: if (error && error.location && michael@0: error.location instanceof Ci.nsIStackFrame) { michael@0: // nsIException has full stack frames in the |.location| member. michael@0: stack = error.location; michael@0: } else { michael@0: // Components.stack to the rescue! michael@0: stack = Components.stack; michael@0: // Remove those top frames that refer to Promise.jsm. michael@0: while (stack) { michael@0: if (!stack.filename.endsWith("/Promise.jsm")) { michael@0: break; michael@0: } michael@0: stack = stack.caller; michael@0: } michael@0: } michael@0: if (stack) { michael@0: let frames = []; michael@0: while (stack) { michael@0: frames.push(stack); michael@0: stack = stack.caller; michael@0: } michael@0: value.stack = frames.join("\n"); michael@0: } michael@0: } michael@0: } catch (ex) { michael@0: // Ignore value michael@0: } michael@0: this._map.set(id, value); michael@0: return id; michael@0: }, michael@0: michael@0: /** michael@0: * Notify all observers that a pending error is now uncaught. michael@0: * michael@0: * @param id The identifier of the pending error, as returned by michael@0: * |register|. michael@0: */ michael@0: report: function(id) { michael@0: let value = this._map.get(id); michael@0: if (!value) { michael@0: return; // The error has already been reported michael@0: } michael@0: this._map.delete(id); michael@0: for (let obs of this._observers.values()) { michael@0: obs(value); michael@0: } michael@0: }, michael@0: michael@0: /** michael@0: * Mark all pending errors are uncaught, notify the observers. michael@0: */ michael@0: flush: function() { michael@0: // Since we are going to modify the map while walking it, michael@0: // let's copying the keys first. michael@0: let keys = [key for (key of this._map.keys())]; michael@0: for (let key of keys) { michael@0: this.report(key); michael@0: } michael@0: }, michael@0: michael@0: /** michael@0: * Stop tracking an error, as this error has been caught, michael@0: * eventually. michael@0: */ michael@0: unregister: function(id) { michael@0: this._map.delete(id); michael@0: }, michael@0: michael@0: /** michael@0: * Add an observer notified when an error is reported as uncaught. michael@0: * michael@0: * @param {function} observer A function notified when an error is michael@0: * reported as uncaught. Its arguments are michael@0: * {message, date, fileName, stack, lineNumber} michael@0: * All arguments are optional. michael@0: */ michael@0: addObserver: function(observer) { michael@0: this._observers.add(observer); michael@0: }, michael@0: michael@0: /** michael@0: * Remove an observer added with addObserver michael@0: */ michael@0: removeObserver: function(observer) { michael@0: this._observers.delete(observer); michael@0: }, michael@0: michael@0: /** michael@0: * Remove all the observers added with addObserver michael@0: */ michael@0: removeAllObservers: function() { michael@0: this._observers.clear(); michael@0: } michael@0: }; michael@0: PendingErrors.init(); michael@0: michael@0: // Default mechanism for displaying errors michael@0: PendingErrors.addObserver(function(details) { michael@0: let error = Cc['@mozilla.org/scripterror;1'].createInstance(Ci.nsIScriptError); michael@0: if (!error || !Services.console) { michael@0: // Too late during shutdown to use the nsIConsole michael@0: dump("*************************\n"); michael@0: dump("A promise chain failed to handle a rejection\n\n"); michael@0: dump("On: " + details.date + "\n"); michael@0: dump("Full message: " + details.message + "\n"); michael@0: dump("See https://developer.mozilla.org/Mozilla/JavaScript_code_modules/Promise.jsm/Promise\n"); michael@0: dump("Full stack: " + (details.stack||"not available") + "\n"); michael@0: dump("*************************\n"); michael@0: return; michael@0: } michael@0: let message = details.message; michael@0: if (details.stack) { michael@0: message += "\nFull Stack: " + details.stack; michael@0: } michael@0: error.init( michael@0: /*message*/"A promise chain failed to handle a rejection.\n\n" + michael@0: "Date: " + details.date + "\nFull Message: " + details.message, michael@0: /*sourceName*/ details.fileName, michael@0: /*sourceLine*/ details.lineNumber?("" + details.lineNumber):0, michael@0: /*lineNumber*/ details.lineNumber || 0, michael@0: /*columnNumber*/ 0, michael@0: /*flags*/ Ci.nsIScriptError.errorFlag, michael@0: /*category*/ "chrome javascript"); michael@0: Services.console.logMessage(error); michael@0: }); michael@0: michael@0: michael@0: ///////// Additional warnings for developers michael@0: // michael@0: // The following error types are considered programmer errors, which should be michael@0: // reported (possibly redundantly) so as to let programmers fix their code. michael@0: const ERRORS_TO_REPORT = ["EvalError", "RangeError", "ReferenceError", "TypeError"]; michael@0: michael@0: //////////////////////////////////////////////////////////////////////////////// michael@0: //// Promise michael@0: michael@0: /** michael@0: * The Promise constructor. Creates a new promise given an executor callback. michael@0: * The executor callback is called with the resolve and reject handlers. michael@0: * michael@0: * @param aExecutor michael@0: * The callback that will be called with resolve and reject. michael@0: */ michael@0: this.Promise = function Promise(aExecutor) michael@0: { michael@0: if (typeof(aExecutor) != "function") { michael@0: throw new TypeError("Promise constructor must be called with an executor."); michael@0: } michael@0: michael@0: /* michael@0: * Internal status of the promise. This can be equal to STATUS_PENDING, michael@0: * STATUS_RESOLVED, or STATUS_REJECTED. michael@0: */ michael@0: Object.defineProperty(this, N_STATUS, { value: STATUS_PENDING, michael@0: writable: true }); michael@0: michael@0: /* michael@0: * When the N_STATUS property is STATUS_RESOLVED, this contains the final michael@0: * resolution value, that cannot be a promise, because resolving with a michael@0: * promise will cause its state to be eventually propagated instead. When the michael@0: * N_STATUS property is STATUS_REJECTED, this contains the final rejection michael@0: * reason, that could be a promise, even if this is uncommon. michael@0: */ michael@0: Object.defineProperty(this, N_VALUE, { writable: true }); michael@0: michael@0: /* michael@0: * Array of Handler objects registered by the "then" method, and not processed michael@0: * yet. Handlers are removed when the promise is resolved or rejected. michael@0: */ michael@0: Object.defineProperty(this, N_HANDLERS, { value: [] }); michael@0: michael@0: /** michael@0: * When the N_STATUS property is STATUS_REJECTED and until there is michael@0: * a rejection callback, this contains an array michael@0: * - {string} id An id for use with |PendingErrors|; michael@0: * - {FinalizationWitness} witness A witness broadcasting |id| on michael@0: * notification "promise-finalization-witness". michael@0: */ michael@0: Object.defineProperty(this, N_WITNESS, { writable: true }); michael@0: michael@0: Object.seal(this); michael@0: michael@0: let resolve = PromiseWalker.completePromise michael@0: .bind(PromiseWalker, this, STATUS_RESOLVED); michael@0: let reject = PromiseWalker.completePromise michael@0: .bind(PromiseWalker, this, STATUS_REJECTED); michael@0: michael@0: try { michael@0: aExecutor.call(undefined, resolve, reject); michael@0: } catch (ex) { michael@0: reject(ex); michael@0: } michael@0: } michael@0: michael@0: /** michael@0: * Calls one of the provided functions as soon as this promise is either michael@0: * resolved or rejected. A new promise is returned, whose state evolves michael@0: * depending on this promise and the provided callback functions. michael@0: * michael@0: * The appropriate callback is always invoked after this method returns, even michael@0: * if this promise is already resolved or rejected. You can also call the michael@0: * "then" method multiple times on the same promise, and the callbacks will be michael@0: * invoked in the same order as they were registered. michael@0: * michael@0: * @param aOnResolve michael@0: * If the promise is resolved, this function is invoked with the michael@0: * resolution value of the promise as its only argument, and the michael@0: * outcome of the function determines the state of the new promise michael@0: * returned by the "then" method. In case this parameter is not a michael@0: * function (usually "null"), the new promise returned by the "then" michael@0: * method is resolved with the same value as the original promise. michael@0: * michael@0: * @param aOnReject michael@0: * If the promise is rejected, this function is invoked with the michael@0: * rejection reason of the promise as its only argument, and the michael@0: * outcome of the function determines the state of the new promise michael@0: * returned by the "then" method. In case this parameter is not a michael@0: * function (usually left "undefined"), the new promise returned by the michael@0: * "then" method is rejected with the same reason as the original michael@0: * promise. michael@0: * michael@0: * @return A new promise that is initially pending, then assumes a state that michael@0: * depends on the outcome of the invoked callback function: michael@0: * - If the callback returns a value that is not a promise, including michael@0: * "undefined", the new promise is resolved with this resolution michael@0: * value, even if the original promise was rejected. michael@0: * - If the callback throws an exception, the new promise is rejected michael@0: * with the exception as the rejection reason, even if the original michael@0: * promise was resolved. michael@0: * - If the callback returns a promise, the new promise will michael@0: * eventually assume the same state as the returned promise. michael@0: * michael@0: * @note If the aOnResolve callback throws an exception, the aOnReject michael@0: * callback is not invoked. You can register a rejection callback on michael@0: * the returned promise instead, to process any exception occurred in michael@0: * either of the callbacks registered on this promise. michael@0: */ michael@0: Promise.prototype.then = function (aOnResolve, aOnReject) michael@0: { michael@0: let handler = new Handler(this, aOnResolve, aOnReject); michael@0: this[N_HANDLERS].push(handler); michael@0: michael@0: // Ensure the handler is scheduled for processing if this promise is already michael@0: // resolved or rejected. michael@0: if (this[N_STATUS] != STATUS_PENDING) { michael@0: michael@0: // This promise is not the last in the chain anymore. Remove any watchdog. michael@0: if (this[N_WITNESS] != null) { michael@0: let [id, witness] = this[N_WITNESS]; michael@0: this[N_WITNESS] = null; michael@0: witness.forget(); michael@0: PendingErrors.unregister(id); michael@0: } michael@0: michael@0: PromiseWalker.schedulePromise(this); michael@0: } michael@0: michael@0: return handler.nextPromise; michael@0: }; michael@0: michael@0: /** michael@0: * Invokes `promise.then` with undefined for the resolve handler and a given michael@0: * reject handler. michael@0: * michael@0: * @param aOnReject michael@0: * The rejection handler. michael@0: * michael@0: * @return A new pending promise returned. michael@0: * michael@0: * @see Promise.prototype.then michael@0: */ michael@0: Promise.prototype.catch = function (aOnReject) michael@0: { michael@0: return this.then(undefined, aOnReject); michael@0: }; michael@0: michael@0: /** michael@0: * Creates a new pending promise and provides methods to resolve or reject it. michael@0: * michael@0: * @return A new object, containing the new promise in the "promise" property, michael@0: * and the methods to change its state in the "resolve" and "reject" michael@0: * properties. See the Deferred documentation for details. michael@0: */ michael@0: Promise.defer = function () michael@0: { michael@0: return new Deferred(); michael@0: }; michael@0: michael@0: /** michael@0: * Creates a new promise resolved with the specified value, or propagates the michael@0: * state of an existing promise. michael@0: * michael@0: * @param aValue michael@0: * If this value is not a promise, including "undefined", it becomes michael@0: * the resolution value of the returned promise. If this value is a michael@0: * promise, then the returned promise will eventually assume the same michael@0: * state as the provided promise. michael@0: * michael@0: * @return A promise that can be pending, resolved, or rejected. michael@0: */ michael@0: Promise.resolve = function (aValue) michael@0: { michael@0: if (aValue && typeof(aValue) == "function" && aValue.isAsyncFunction) { michael@0: throw new TypeError( michael@0: "Cannot resolve a promise with an async function. " + michael@0: "You should either invoke the async function first " + michael@0: "or use 'Task.spawn' instead of 'Task.async' to start " + michael@0: "the Task and return its promise."); michael@0: } michael@0: michael@0: if (aValue instanceof Promise) { michael@0: return aValue; michael@0: } michael@0: michael@0: return new Promise((aResolve) => aResolve(aValue)); michael@0: }; michael@0: michael@0: /** michael@0: * Creates a new promise rejected with the specified reason. michael@0: * michael@0: * @param aReason michael@0: * The rejection reason for the returned promise. Although the reason michael@0: * can be "undefined", it is generally an Error object, like in michael@0: * exception handling. michael@0: * michael@0: * @return A rejected promise. michael@0: * michael@0: * @note The aReason argument should not be a promise. Using a rejected michael@0: * promise for the value of aReason would make the rejection reason michael@0: * equal to the rejected promise itself, and not its rejection reason. michael@0: */ michael@0: Promise.reject = function (aReason) michael@0: { michael@0: return new Promise((_, aReject) => aReject(aReason)); michael@0: }; michael@0: michael@0: /** michael@0: * Returns a promise that is resolved or rejected when all values are michael@0: * resolved or any is rejected. michael@0: * michael@0: * @param aValues michael@0: * Iterable of promises that may be pending, resolved, or rejected. When michael@0: * all are resolved or any is rejected, the returned promise will be michael@0: * resolved or rejected as well. michael@0: * michael@0: * @return A new promise that is fulfilled when all values are resolved or michael@0: * that is rejected when any of the values are rejected. Its michael@0: * resolution value will be an array of all resolved values in the michael@0: * given order, or undefined if aValues is an empty array. The reject michael@0: * reason will be forwarded from the first promise in the list of michael@0: * given promises to be rejected. michael@0: */ michael@0: Promise.all = function (aValues) michael@0: { michael@0: if (aValues == null || typeof(aValues["@@iterator"]) != "function") { michael@0: throw new Error("Promise.all() expects an iterable."); michael@0: } michael@0: michael@0: return new Promise((resolve, reject) => { michael@0: let values = Array.isArray(aValues) ? aValues : [...aValues]; michael@0: let countdown = values.length; michael@0: let resolutionValues = new Array(countdown); michael@0: michael@0: if (!countdown) { michael@0: resolve(resolutionValues); michael@0: return; michael@0: } michael@0: michael@0: function checkForCompletion(aValue, aIndex) { michael@0: resolutionValues[aIndex] = aValue; michael@0: if (--countdown === 0) { michael@0: resolve(resolutionValues); michael@0: } michael@0: } michael@0: michael@0: for (let i = 0; i < values.length; i++) { michael@0: let index = i; michael@0: let value = values[i]; michael@0: let resolver = val => checkForCompletion(val, index); michael@0: michael@0: if (value && typeof(value.then) == "function") { michael@0: value.then(resolver, reject); michael@0: } else { michael@0: // Given value is not a promise, forward it as a resolution value. michael@0: resolver(value); michael@0: } michael@0: } michael@0: }); michael@0: }; michael@0: michael@0: /** michael@0: * Returns a promise that is resolved or rejected when the first value is michael@0: * resolved or rejected, taking on the value or reason of that promise. michael@0: * michael@0: * @param aValues michael@0: * Iterable of values or promises that may be pending, resolved, or michael@0: * rejected. When any is resolved or rejected, the returned promise will michael@0: * be resolved or rejected as to the given value or reason. michael@0: * michael@0: * @return A new promise that is fulfilled when any values are resolved or michael@0: * rejected. Its resolution value will be forwarded from the resolution michael@0: * value or rejection reason. michael@0: */ michael@0: Promise.race = function (aValues) michael@0: { michael@0: if (aValues == null || typeof(aValues["@@iterator"]) != "function") { michael@0: throw new Error("Promise.race() expects an iterable."); michael@0: } michael@0: michael@0: return new Promise((resolve, reject) => { michael@0: for (let value of aValues) { michael@0: Promise.resolve(value).then(resolve, reject); michael@0: } michael@0: }); michael@0: }; michael@0: michael@0: Promise.Debugging = { michael@0: /** michael@0: * Add an observer notified when an error is reported as uncaught. michael@0: * michael@0: * @param {function} observer A function notified when an error is michael@0: * reported as uncaught. Its arguments are michael@0: * {message, date, fileName, stack, lineNumber} michael@0: * All arguments are optional. michael@0: */ michael@0: addUncaughtErrorObserver: function(observer) { michael@0: PendingErrors.addObserver(observer); michael@0: }, michael@0: michael@0: /** michael@0: * Remove an observer added with addUncaughtErrorObserver michael@0: * michael@0: * @param {function} An observer registered with michael@0: * addUncaughtErrorObserver. michael@0: */ michael@0: removeUncaughtErrorObserver: function(observer) { michael@0: PendingErrors.removeObserver(observer); michael@0: }, michael@0: michael@0: /** michael@0: * Remove all the observers added with addUncaughtErrorObserver michael@0: */ michael@0: clearUncaughtErrorObservers: function() { michael@0: PendingErrors.removeAllObservers(); michael@0: }, michael@0: michael@0: /** michael@0: * Force all pending errors to be reported immediately as uncaught. michael@0: * Note that this may cause some false positives. michael@0: */ michael@0: flushUncaughtErrors: function() { michael@0: PendingErrors.flush(); michael@0: }, michael@0: }; michael@0: Object.freeze(Promise.Debugging); michael@0: michael@0: Object.freeze(Promise); michael@0: michael@0: //////////////////////////////////////////////////////////////////////////////// michael@0: //// PromiseWalker michael@0: michael@0: /** michael@0: * This singleton object invokes the handlers registered on resolved and michael@0: * rejected promises, ensuring that processing is not recursive and is done in michael@0: * the same order as registration occurred on each promise. michael@0: * michael@0: * There is no guarantee on the order of execution of handlers registered on michael@0: * different promises. michael@0: */ michael@0: this.PromiseWalker = { michael@0: /** michael@0: * Singleton array of all the unprocessed handlers currently registered on michael@0: * resolved or rejected promises. Handlers are removed from the array as soon michael@0: * as they are processed. michael@0: */ michael@0: handlers: [], michael@0: michael@0: /** michael@0: * Called when a promise needs to change state to be resolved or rejected. michael@0: * michael@0: * @param aPromise michael@0: * Promise that needs to change state. If this is already resolved or michael@0: * rejected, this method has no effect. michael@0: * @param aStatus michael@0: * New desired status, either STATUS_RESOLVED or STATUS_REJECTED. michael@0: * @param aValue michael@0: * Associated resolution value or rejection reason. michael@0: */ michael@0: completePromise: function (aPromise, aStatus, aValue) michael@0: { michael@0: // Do nothing if the promise is already resolved or rejected. michael@0: if (aPromise[N_STATUS] != STATUS_PENDING) { michael@0: return; michael@0: } michael@0: michael@0: // Resolving with another promise will cause this promise to eventually michael@0: // assume the state of the provided promise. michael@0: if (aStatus == STATUS_RESOLVED && aValue && michael@0: typeof(aValue.then) == "function") { michael@0: aValue.then(this.completePromise.bind(this, aPromise, STATUS_RESOLVED), michael@0: this.completePromise.bind(this, aPromise, STATUS_REJECTED)); michael@0: return; michael@0: } michael@0: michael@0: // Change the promise status and schedule our handlers for processing. michael@0: aPromise[N_STATUS] = aStatus; michael@0: aPromise[N_VALUE] = aValue; michael@0: if (aPromise[N_HANDLERS].length > 0) { michael@0: this.schedulePromise(aPromise); michael@0: } else if (aStatus == STATUS_REJECTED) { michael@0: // This is a rejection and the promise is the last in the chain. michael@0: // For the time being we therefore have an uncaught error. michael@0: let id = PendingErrors.register(aValue); michael@0: let witness = michael@0: FinalizationWitnessService.make("promise-finalization-witness", id); michael@0: aPromise[N_WITNESS] = [id, witness]; michael@0: } michael@0: }, michael@0: michael@0: /** michael@0: * Sets up the PromiseWalker loop to start on the next tick of the event loop michael@0: */ michael@0: scheduleWalkerLoop: function() michael@0: { michael@0: this.walkerLoopScheduled = true; michael@0: Services.tm.currentThread.dispatch(this.walkerLoop, michael@0: Ci.nsIThread.DISPATCH_NORMAL); michael@0: }, michael@0: michael@0: /** michael@0: * Schedules the resolution or rejection handlers registered on the provided michael@0: * promise for processing. michael@0: * michael@0: * @param aPromise michael@0: * Resolved or rejected promise whose handlers should be processed. It michael@0: * is expected that this promise has at least one handler to process. michael@0: */ michael@0: schedulePromise: function (aPromise) michael@0: { michael@0: // Migrate the handlers from the provided promise to the global list. michael@0: for (let handler of aPromise[N_HANDLERS]) { michael@0: this.handlers.push(handler); michael@0: } michael@0: aPromise[N_HANDLERS].length = 0; michael@0: michael@0: // Schedule the walker loop on the next tick of the event loop. michael@0: if (!this.walkerLoopScheduled) { michael@0: this.scheduleWalkerLoop(); michael@0: } michael@0: }, michael@0: michael@0: /** michael@0: * Indicates whether the walker loop is currently scheduled for execution on michael@0: * the next tick of the event loop. michael@0: */ michael@0: walkerLoopScheduled: false, michael@0: michael@0: /** michael@0: * Processes all the known handlers during this tick of the event loop. This michael@0: * eager processing is done to avoid unnecessarily exiting and re-entering the michael@0: * JavaScript context for each handler on a resolved or rejected promise. michael@0: * michael@0: * This function is called with "this" bound to the PromiseWalker object. michael@0: */ michael@0: walkerLoop: function () michael@0: { michael@0: // If there is more than one handler waiting, reschedule the walker loop michael@0: // immediately. Otherwise, use walkerLoopScheduled to tell schedulePromise() michael@0: // to reschedule the loop if it adds more handlers to the queue. This makes michael@0: // this walker resilient to the case where one handler does not return, but michael@0: // starts a nested event loop. In that case, the newly scheduled walker will michael@0: // take over. In the common case, the newly scheduled walker will be invoked michael@0: // after this one has returned, with no actual handler to process. This michael@0: // small overhead is required to make nested event loops work correctly, but michael@0: // occurs at most once per resolution chain, thus having only a minor michael@0: // impact on overall performance. michael@0: if (this.handlers.length > 1) { michael@0: this.scheduleWalkerLoop(); michael@0: } else { michael@0: this.walkerLoopScheduled = false; michael@0: } michael@0: michael@0: // Process all the known handlers eagerly. michael@0: while (this.handlers.length > 0) { michael@0: this.handlers.shift().process(); michael@0: } michael@0: }, michael@0: }; michael@0: michael@0: // Bind the function to the singleton once. michael@0: PromiseWalker.walkerLoop = PromiseWalker.walkerLoop.bind(PromiseWalker); michael@0: michael@0: //////////////////////////////////////////////////////////////////////////////// michael@0: //// Deferred michael@0: michael@0: /** michael@0: * Returned by "Promise.defer" to provide a new promise along with methods to michael@0: * change its state. michael@0: */ michael@0: function Deferred() michael@0: { michael@0: this.promise = new Promise((aResolve, aReject) => { michael@0: this.resolve = aResolve; michael@0: this.reject = aReject; michael@0: }); michael@0: Object.freeze(this); michael@0: } michael@0: michael@0: Deferred.prototype = { michael@0: /** michael@0: * A newly created promise, initially in the pending state. michael@0: */ michael@0: promise: null, michael@0: michael@0: /** michael@0: * Resolves the associated promise with the specified value, or propagates the michael@0: * state of an existing promise. If the associated promise has already been michael@0: * resolved or rejected, this method does nothing. michael@0: * michael@0: * This function is bound to its associated promise when "Promise.defer" is michael@0: * called, and can be called with any value of "this". michael@0: * michael@0: * @param aValue michael@0: * If this value is not a promise, including "undefined", it becomes michael@0: * the resolution value of the associated promise. If this value is a michael@0: * promise, then the associated promise will eventually assume the same michael@0: * state as the provided promise. michael@0: * michael@0: * @note Calling this method with a pending promise as the aValue argument, michael@0: * and then calling it again with another value before the promise is michael@0: * resolved or rejected, has unspecified behavior and should be avoided. michael@0: */ michael@0: resolve: null, michael@0: michael@0: /** michael@0: * Rejects the associated promise with the specified reason. If the promise michael@0: * has already been resolved or rejected, this method does nothing. michael@0: * michael@0: * This function is bound to its associated promise when "Promise.defer" is michael@0: * called, and can be called with any value of "this". michael@0: * michael@0: * @param aReason michael@0: * The rejection reason for the associated promise. Although the michael@0: * reason can be "undefined", it is generally an Error object, like in michael@0: * exception handling. michael@0: * michael@0: * @note The aReason argument should not generally be a promise. In fact, michael@0: * using a rejected promise for the value of aReason would make the michael@0: * rejection reason equal to the rejected promise itself, not to the michael@0: * rejection reason of the rejected promise. michael@0: */ michael@0: reject: null, michael@0: }; michael@0: michael@0: //////////////////////////////////////////////////////////////////////////////// michael@0: //// Handler michael@0: michael@0: /** michael@0: * Handler registered on a promise by the "then" function. michael@0: */ michael@0: function Handler(aThisPromise, aOnResolve, aOnReject) michael@0: { michael@0: this.thisPromise = aThisPromise; michael@0: this.onResolve = aOnResolve; michael@0: this.onReject = aOnReject; michael@0: this.nextPromise = new Promise(() => {}); michael@0: } michael@0: michael@0: Handler.prototype = { michael@0: /** michael@0: * Promise on which the "then" method was called. michael@0: */ michael@0: thisPromise: null, michael@0: michael@0: /** michael@0: * Unmodified resolution handler provided to the "then" method. michael@0: */ michael@0: onResolve: null, michael@0: michael@0: /** michael@0: * Unmodified rejection handler provided to the "then" method. michael@0: */ michael@0: onReject: null, michael@0: michael@0: /** michael@0: * New promise that will be returned by the "then" method. michael@0: */ michael@0: nextPromise: null, michael@0: michael@0: /** michael@0: * Called after thisPromise is resolved or rejected, invokes the appropriate michael@0: * callback and propagates the result to nextPromise. michael@0: */ michael@0: process: function() michael@0: { michael@0: // The state of this promise is propagated unless a handler is defined. michael@0: let nextStatus = this.thisPromise[N_STATUS]; michael@0: let nextValue = this.thisPromise[N_VALUE]; michael@0: michael@0: try { michael@0: // If a handler is defined for either resolution or rejection, invoke it michael@0: // to determine the state of the next promise, that will be resolved with michael@0: // the returned value, that can also be another promise. michael@0: if (nextStatus == STATUS_RESOLVED) { michael@0: if (typeof(this.onResolve) == "function") { michael@0: nextValue = this.onResolve.call(undefined, nextValue); michael@0: } michael@0: } else if (typeof(this.onReject) == "function") { michael@0: nextValue = this.onReject.call(undefined, nextValue); michael@0: nextStatus = STATUS_RESOLVED; michael@0: } michael@0: } catch (ex) { michael@0: michael@0: // An exception has occurred in the handler. michael@0: michael@0: if (ex && typeof ex == "object" && "name" in ex && michael@0: ERRORS_TO_REPORT.indexOf(ex.name) != -1) { michael@0: michael@0: // We suspect that the exception is a programmer error, so we now michael@0: // display it using dump(). Note that we do not use Cu.reportError as michael@0: // we assume that this is a programming error, so we do not want end michael@0: // users to see it. Also, if the programmer handles errors correctly, michael@0: // they will either treat the error or log them somewhere. michael@0: michael@0: dump("*************************\n"); michael@0: dump("A coding exception was thrown in a Promise " + michael@0: ((nextStatus == STATUS_RESOLVED) ? "resolution":"rejection") + michael@0: " callback.\n\n"); michael@0: dump("Full message: " + ex + "\n"); michael@0: dump("See https://developer.mozilla.org/Mozilla/JavaScript_code_modules/Promise.jsm/Promise\n"); michael@0: dump("Full stack: " + (("stack" in ex)?ex.stack:"not available") + "\n"); michael@0: dump("*************************\n"); michael@0: michael@0: } michael@0: michael@0: // Additionally, reject the next promise. michael@0: nextStatus = STATUS_REJECTED; michael@0: nextValue = ex; michael@0: } michael@0: michael@0: // Propagate the newly determined state to the next promise. michael@0: PromiseWalker.completePromise(this.nextPromise, nextStatus, nextValue); michael@0: }, michael@0: };