1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 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/. */
8 * This file was copied from Firefox 26.0. However, it was modified
9 * slightly to use only syntax compatible with Firefox 4.0.
14 this.EXPORTED_SYMBOLS = [
19 * This module implements the "promise" construct, according to the
20 * "Promises/A+" proposal as known in April 2013, documented here:
22 * <http://promises-aplus.github.com/promises-spec/>
24 * A promise is an object representing a value that may not be available yet.
25 * Internally, a promise can be in one of three states:
27 * - Pending, when the final value is not available yet. This is the only state
28 * that may transition to one of the other two states.
30 * - Resolved, when and if the final value becomes available. A resolution
31 * value becomes permanently associated with the promise. This may be any
32 * value, including "undefined".
34 * - Rejected, if an error prevented the final value from being determined. A
35 * rejection reason becomes permanently associated with the promise. This may
36 * be any value, including "undefined", though it is generally an Error
37 * object, like in exception handling.
39 * A reference to an existing promise may be received by different means, for
40 * example as the return value of a call into an asynchronous API. In this
41 * case, the state of the promise can be observed but not directly controlled.
43 * To observe the state of a promise, its "then" method must be used. This
44 * method registers callback functions that are called as soon as the promise is
45 * either resolved or rejected. The method returns a new promise, that in turn
46 * is resolved or rejected depending on the state of the original promise and on
47 * the behavior of the callbacks. For example, unhandled exceptions in the
48 * callbacks cause the new promise to be rejected, even if the original promise
49 * is resolved. See the documentation of the "then" method for details.
51 * Promises may also be created using the "Promise.defer" function, the main
52 * entry point of this module. The function, along with the new promise,
53 * returns separate methods to change its state to be resolved or rejected.
54 * See the documentation of the "Deferred" prototype for details.
56 * -----------------------------------------------------------------------------
58 * Cu.import("resource://gre/modules/Promise.jsm");
60 * // This function creates and returns a new promise.
61 * function promiseValueAfterTimeout(aValue, aTimeout)
63 * let deferred = Promise.defer();
66 * // An asynchronous operation will trigger the resolution of the promise.
67 * // In this example, we don't have a callback that triggers a rejection.
68 * do_timeout(aTimeout, function () {
69 * deferred.resolve(aValue);
72 * // Generally, functions returning promises propagate exceptions through
73 * // the returned promise, though they may also choose to fail early.
74 * deferred.reject(ex);
77 * // We don't return the deferred to the caller, but only the contained
78 * // promise, so that the caller cannot accidentally change its state.
79 * return deferred.promise;
82 * // This code uses the promise returned be the function above.
83 * let promise = promiseValueAfterTimeout("Value", 1000);
85 * let newPromise = promise.then(function onResolve(aValue) {
86 * do_print("Resolved with this value: " + aValue);
87 * }, function onReject(aReason) {
88 * do_print("Rejected with this reason: " + aReason);
91 * // Unexpected errors should always be reported at the end of a promise chain.
92 * newPromise.then(null, Components.utils.reportError);
94 * -----------------------------------------------------------------------------
97 ////////////////////////////////////////////////////////////////////////////////
100 const Cc = Components.classes;
101 const Ci = Components.interfaces;
102 const Cu = Components.utils;
103 const Cr = Components.results;
105 Cu.import("resource://gre/modules/Services.jsm");
107 const STATUS_PENDING = 0;
108 const STATUS_RESOLVED = 1;
109 const STATUS_REJECTED = 2;
111 // These "private names" allow some properties of the Promise object to be
112 // accessed only by this module, while still being visible on the object
113 // manually when using a debugger. They don't strictly guarantee that the
114 // properties are inaccessible by other code, but provide enough protection to
115 // avoid using them by mistake.
116 const salt = Math.floor(Math.random() * 100);
117 const Name = function (n) { return "{private:" + n + ":" + salt + "}"; }
118 const N_STATUS = Name("status");
119 const N_VALUE = Name("value");
120 const N_HANDLERS = Name("handlers");
122 // The following error types are considered programmer errors, which should be
123 // reported (possibly redundantly) so as to let programmers fix their code.
124 const ERRORS_TO_REPORT = ["EvalError", "RangeError", "ReferenceError", "TypeError"];
126 ////////////////////////////////////////////////////////////////////////////////
130 * This object provides the public module functions.
132 this.Promise = Object.freeze({
134 * Creates a new pending promise and provides methods to resolve or reject it.
136 * @return A new object, containing the new promise in the "promise" property,
137 * and the methods to change its state in the "resolve" and "reject"
138 * properties. See the Deferred documentation for details.
142 return new Deferred();
146 * Creates a new promise resolved with the specified value, or propagates the
147 * state of an existing promise.
150 * If this value is not a promise, including "undefined", it becomes
151 * the resolution value of the returned promise. If this value is a
152 * promise, then the returned promise will eventually assume the same
153 * state as the provided promise.
155 * @return A promise that can be pending, resolved, or rejected.
157 resolve: function (aValue)
159 let promise = new PromiseImpl();
160 PromiseWalker.completePromise(promise, STATUS_RESOLVED, aValue);
165 * Creates a new promise rejected with the specified reason.
168 * The rejection reason for the returned promise. Although the reason
169 * can be "undefined", it is generally an Error object, like in
170 * exception handling.
172 * @return A rejected promise.
174 * @note The aReason argument should not be a promise. Using a rejected
175 * promise for the value of aReason would make the rejection reason
176 * equal to the rejected promise itself, and not its rejection reason.
178 reject: function (aReason)
180 let promise = new PromiseImpl();
181 PromiseWalker.completePromise(promise, STATUS_REJECTED, aReason);
186 * Returns a promise that is resolved or rejected when all values are
187 * resolved or any is rejected.
190 * Array of promises that may be pending, resolved, or rejected. When
191 * all are resolved or any is rejected, the returned promise will be
192 * resolved or rejected as well.
194 * @return A new promise that is fulfilled when all values are resolved or
195 * that is rejected when any of the values are rejected. Its
196 * resolution value will be an array of all resolved values in the
197 * given order, or undefined if aValues is an empty array. The reject
198 * reason will be forwarded from the first promise in the list of
199 * given promises to be rejected.
201 all: function (aValues)
203 if (!Array.isArray(aValues)) {
204 throw new Error("Promise.all() expects an array of promises or values.");
207 if (!aValues.length) {
208 return Promise.resolve([]);
211 let countdown = aValues.length;
212 let deferred = Promise.defer();
213 let resolutionValues = new Array(countdown);
215 function checkForCompletion(aValue, aIndex) {
216 resolutionValues[aIndex] = aValue;
218 if (--countdown === 0) {
219 deferred.resolve(resolutionValues);
223 for (let i = 0; i < aValues.length; i++) {
225 let value = aValues[i];
226 let resolve = function (val) { return checkForCompletion(val, index); };
228 if (value && typeof(value.then) == "function") {
229 value.then(resolve, deferred.reject);
231 // Given value is not a promise, forward it as a resolution value.
236 return deferred.promise;
240 ////////////////////////////////////////////////////////////////////////////////
244 * This singleton object invokes the handlers registered on resolved and
245 * rejected promises, ensuring that processing is not recursive and is done in
246 * the same order as registration occurred on each promise.
248 * There is no guarantee on the order of execution of handlers registered on
249 * different promises.
251 this.PromiseWalker = {
253 * Singleton array of all the unprocessed handlers currently registered on
254 * resolved or rejected promises. Handlers are removed from the array as soon
255 * as they are processed.
260 * Called when a promise needs to change state to be resolved or rejected.
263 * Promise that needs to change state. If this is already resolved or
264 * rejected, this method has no effect.
266 * New desired status, either STATUS_RESOLVED or STATUS_REJECTED.
268 * Associated resolution value or rejection reason.
270 completePromise: function (aPromise, aStatus, aValue)
272 // Do nothing if the promise is already resolved or rejected.
273 if (aPromise[N_STATUS] != STATUS_PENDING) {
277 // Resolving with another promise will cause this promise to eventually
278 // assume the state of the provided promise.
279 if (aStatus == STATUS_RESOLVED && aValue &&
280 typeof(aValue.then) == "function") {
281 aValue.then(this.completePromise.bind(this, aPromise, STATUS_RESOLVED),
282 this.completePromise.bind(this, aPromise, STATUS_REJECTED));
286 // Change the promise status and schedule our handlers for processing.
287 aPromise[N_STATUS] = aStatus;
288 aPromise[N_VALUE] = aValue;
289 if (aPromise[N_HANDLERS].length > 0) {
290 this.schedulePromise(aPromise);
295 * Sets up the PromiseWalker loop to start on the next tick of the event loop
297 scheduleWalkerLoop: function()
299 this.walkerLoopScheduled = true;
300 Services.tm.currentThread.dispatch(this.walkerLoop,
301 Ci.nsIThread.DISPATCH_NORMAL);
305 * Schedules the resolution or rejection handlers registered on the provided
306 * promise for processing.
309 * Resolved or rejected promise whose handlers should be processed. It
310 * is expected that this promise has at least one handler to process.
312 schedulePromise: function (aPromise)
314 // Migrate the handlers from the provided promise to the global list.
315 let handlers = aPromise[N_HANDLERS];
316 for (let i in handlers) {
317 this.handlers.push(handlers[i]);
319 aPromise[N_HANDLERS].length = 0;
321 // Schedule the walker loop on the next tick of the event loop.
322 if (!this.walkerLoopScheduled) {
323 this.scheduleWalkerLoop();
328 * Indicates whether the walker loop is currently scheduled for execution on
329 * the next tick of the event loop.
331 walkerLoopScheduled: false,
334 * Processes all the known handlers during this tick of the event loop. This
335 * eager processing is done to avoid unnecessarily exiting and re-entering the
336 * JavaScript context for each handler on a resolved or rejected promise.
338 * This function is called with "this" bound to the PromiseWalker object.
340 walkerLoop: function ()
342 // If there is more than one handler waiting, reschedule the walker loop
343 // immediately. Otherwise, use walkerLoopScheduled to tell schedulePromise()
344 // to reschedule the loop if it adds more handlers to the queue. This makes
345 // this walker resilient to the case where one handler does not return, but
346 // starts a nested event loop. In that case, the newly scheduled walker will
347 // take over. In the common case, the newly scheduled walker will be invoked
348 // after this one has returned, with no actual handler to process. This
349 // small overhead is required to make nested event loops work correctly, but
350 // occurs at most once per resolution chain, thus having only a minor
351 // impact on overall performance.
352 if (this.handlers.length > 1) {
353 this.scheduleWalkerLoop();
355 this.walkerLoopScheduled = false;
358 // Process all the known handlers eagerly.
359 while (this.handlers.length > 0) {
360 this.handlers.shift().process();
365 // Bind the function to the singleton once.
366 PromiseWalker.walkerLoop = PromiseWalker.walkerLoop.bind(PromiseWalker);
368 ////////////////////////////////////////////////////////////////////////////////
372 * Returned by "Promise.defer" to provide a new promise along with methods to
377 this.promise = new PromiseImpl();
378 this.resolve = this.resolve.bind(this);
379 this.reject = this.reject.bind(this);
384 Deferred.prototype = {
386 * A newly created promise, initially in the pending state.
391 * Resolves the associated promise with the specified value, or propagates the
392 * state of an existing promise. If the associated promise has already been
393 * resolved or rejected, this method does nothing.
395 * This function is bound to its associated promise when "Promise.defer" is
396 * called, and can be called with any value of "this".
399 * If this value is not a promise, including "undefined", it becomes
400 * the resolution value of the associated promise. If this value is a
401 * promise, then the associated promise will eventually assume the same
402 * state as the provided promise.
404 * @note Calling this method with a pending promise as the aValue argument,
405 * and then calling it again with another value before the promise is
406 * resolved or rejected, has unspecified behavior and should be avoided.
408 resolve: function (aValue) {
409 PromiseWalker.completePromise(this.promise, STATUS_RESOLVED, aValue);
413 * Rejects the associated promise with the specified reason. If the promise
414 * has already been resolved or rejected, this method does nothing.
416 * This function is bound to its associated promise when "Promise.defer" is
417 * called, and can be called with any value of "this".
420 * The rejection reason for the associated promise. Although the
421 * reason can be "undefined", it is generally an Error object, like in
422 * exception handling.
424 * @note The aReason argument should not generally be a promise. In fact,
425 * using a rejected promise for the value of aReason would make the
426 * rejection reason equal to the rejected promise itself, not to the
427 * rejection reason of the rejected promise.
429 reject: function (aReason) {
430 PromiseWalker.completePromise(this.promise, STATUS_REJECTED, aReason);
434 ////////////////////////////////////////////////////////////////////////////////
438 * The promise object implementation. This includes the public "then" method,
439 * as well as private state properties.
441 function PromiseImpl()
444 * Internal status of the promise. This can be equal to STATUS_PENDING,
445 * STATUS_RESOLVED, or STATUS_REJECTED.
447 Object.defineProperty(this, N_STATUS, { value: STATUS_PENDING,
451 * When the N_STATUS property is STATUS_RESOLVED, this contains the final
452 * resolution value, that cannot be a promise, because resolving with a
453 * promise will cause its state to be eventually propagated instead. When the
454 * N_STATUS property is STATUS_REJECTED, this contains the final rejection
455 * reason, that could be a promise, even if this is uncommon.
457 Object.defineProperty(this, N_VALUE, { writable: true });
460 * Array of Handler objects registered by the "then" method, and not processed
461 * yet. Handlers are removed when the promise is resolved or rejected.
463 Object.defineProperty(this, N_HANDLERS, { value: [] });
468 PromiseImpl.prototype = {
470 * Calls one of the provided functions as soon as this promise is either
471 * resolved or rejected. A new promise is returned, whose state evolves
472 * depending on this promise and the provided callback functions.
474 * The appropriate callback is always invoked after this method returns, even
475 * if this promise is already resolved or rejected. You can also call the
476 * "then" method multiple times on the same promise, and the callbacks will be
477 * invoked in the same order as they were registered.
480 * If the promise is resolved, this function is invoked with the
481 * resolution value of the promise as its only argument, and the
482 * outcome of the function determines the state of the new promise
483 * returned by the "then" method. In case this parameter is not a
484 * function (usually "null"), the new promise returned by the "then"
485 * method is resolved with the same value as the original promise.
488 * If the promise is rejected, this function is invoked with the
489 * rejection reason of the promise as its only argument, and the
490 * outcome of the function determines the state of the new promise
491 * returned by the "then" method. In case this parameter is not a
492 * function (usually left "undefined"), the new promise returned by the
493 * "then" method is rejected with the same reason as the original
496 * @return A new promise that is initially pending, then assumes a state that
497 * depends on the outcome of the invoked callback function:
498 * - If the callback returns a value that is not a promise, including
499 * "undefined", the new promise is resolved with this resolution
500 * value, even if the original promise was rejected.
501 * - If the callback throws an exception, the new promise is rejected
502 * with the exception as the rejection reason, even if the original
503 * promise was resolved.
504 * - If the callback returns a promise, the new promise will
505 * eventually assume the same state as the returned promise.
507 * @note If the aOnResolve callback throws an exception, the aOnReject
508 * callback is not invoked. You can register a rejection callback on
509 * the returned promise instead, to process any exception occurred in
510 * either of the callbacks registered on this promise.
512 then: function (aOnResolve, aOnReject)
514 let handler = new Handler(this, aOnResolve, aOnReject);
515 this[N_HANDLERS].push(handler);
517 // Ensure the handler is scheduled for processing if this promise is already
518 // resolved or rejected.
519 if (this[N_STATUS] != STATUS_PENDING) {
520 PromiseWalker.schedulePromise(this);
523 return handler.nextPromise;
527 ////////////////////////////////////////////////////////////////////////////////
531 * Handler registered on a promise by the "then" function.
533 function Handler(aThisPromise, aOnResolve, aOnReject)
535 this.thisPromise = aThisPromise;
536 this.onResolve = aOnResolve;
537 this.onReject = aOnReject;
538 this.nextPromise = new PromiseImpl();
541 Handler.prototype = {
543 * Promise on which the "then" method was called.
548 * Unmodified resolution handler provided to the "then" method.
553 * Unmodified rejection handler provided to the "then" method.
558 * New promise that will be returned by the "then" method.
563 * Called after thisPromise is resolved or rejected, invokes the appropriate
564 * callback and propagates the result to nextPromise.
568 // The state of this promise is propagated unless a handler is defined.
569 let nextStatus = this.thisPromise[N_STATUS];
570 let nextValue = this.thisPromise[N_VALUE];
573 // If a handler is defined for either resolution or rejection, invoke it
574 // to determine the state of the next promise, that will be resolved with
575 // the returned value, that can also be another promise.
576 if (nextStatus == STATUS_RESOLVED) {
577 if (typeof(this.onResolve) == "function") {
578 nextValue = this.onResolve(nextValue);
580 } else if (typeof(this.onReject) == "function") {
581 nextValue = this.onReject(nextValue);
582 nextStatus = STATUS_RESOLVED;
586 // An exception has occurred in the handler.
588 if (ex && typeof ex == "object" && "name" in ex &&
589 ERRORS_TO_REPORT.indexOf(ex.name) != -1) {
591 // We suspect that the exception is a programmer error, so we now
592 // display it using dump(). Note that we do not use Cu.reportError as
593 // we assume that this is a programming error, so we do not want end
594 // users to see it. Also, if the programmer handles errors correctly,
595 // they will either treat the error or log them somewhere.
597 dump("A coding exception was thrown in a Promise " +
598 ((nextStatus == STATUS_RESOLVED) ? "resolution":"rejection") +
600 dump("Full message: " + ex + "\n");
601 dump("See https://developer.mozilla.org/Mozilla/JavaScript_code_modules/Promise.jsm/Promise\n");
602 dump("Full stack: " + (("stack" in ex)?ex.stack:"not available") + "\n");
605 // Additionally, reject the next promise.
606 nextStatus = STATUS_REJECTED;
610 // Propagate the newly determined state to the next promise.
611 PromiseWalker.completePromise(this.nextPromise, nextStatus, nextValue);