Update coroutines to support Promises, cancelation
[conkeror.git] / modules / compat / Promise.jsm
blob25c1f75b097fb8e60b318b9810c051993466e397
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/. */
7 /**
8  * This file was copied from Firefox 26.0.  However, it was modified
9  * slightly to use only syntax compatible with Firefox 4.0.
10  **/
12 "use strict";
14 this.EXPORTED_SYMBOLS = [
15   "Promise"
18 /**
19  * This module implements the "promise" construct, according to the
20  * "Promises/A+" proposal as known in April 2013, documented here:
21  *
22  * <http://promises-aplus.github.com/promises-spec/>
23  *
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:
26  *
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.
29  *
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".
33  *
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.
38  *
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.
42  *
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.
50  *
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.
55  *
56  * -----------------------------------------------------------------------------
57  *
58  * Cu.import("resource://gre/modules/Promise.jsm");
59  *
60  * // This function creates and returns a new promise.
61  * function promiseValueAfterTimeout(aValue, aTimeout)
62  * {
63  *   let deferred = Promise.defer();
64  *
65  *   try {
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);
70  *     });
71  *   } catch (ex) {
72  *     // Generally, functions returning promises propagate exceptions through
73  *     // the returned promise, though they may also choose to fail early.
74  *     deferred.reject(ex);
75  *   }
76  *
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;
80  * }
81  *
82  * // This code uses the promise returned be the function above.
83  * let promise = promiseValueAfterTimeout("Value", 1000);
84  *
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);
89  * });
90  *
91  * // Unexpected errors should always be reported at the end of a promise chain.
92  * newPromise.then(null, Components.utils.reportError);
93  *
94  * -----------------------------------------------------------------------------
95  */
97 ////////////////////////////////////////////////////////////////////////////////
98 //// Globals
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 ////////////////////////////////////////////////////////////////////////////////
127 //// Promise
130  * This object provides the public module functions.
131  */
132 this.Promise = Object.freeze({
133   /**
134    * Creates a new pending promise and provides methods to resolve or reject it.
135    *
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.
139    */
140   defer: function ()
141   {
142     return new Deferred();
143   },
145   /**
146    * Creates a new promise resolved with the specified value, or propagates the
147    * state of an existing promise.
148    *
149    * @param aValue
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.
154    *
155    * @return A promise that can be pending, resolved, or rejected.
156    */
157   resolve: function (aValue)
158   {
159     let promise = new PromiseImpl();
160     PromiseWalker.completePromise(promise, STATUS_RESOLVED, aValue);
161     return promise;
162   },
164   /**
165    * Creates a new promise rejected with the specified reason.
166    *
167    * @param aReason
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.
171    *
172    * @return A rejected promise.
173    *
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.
177    */
178   reject: function (aReason)
179   {
180     let promise = new PromiseImpl();
181     PromiseWalker.completePromise(promise, STATUS_REJECTED, aReason);
182     return promise;
183   },
185   /**
186    * Returns a promise that is resolved or rejected when all values are
187    * resolved or any is rejected.
188    *
189    * @param aValues
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.
193    *
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.
200    */
201   all: function (aValues)
202   {
203     if (!Array.isArray(aValues)) {
204       throw new Error("Promise.all() expects an array of promises or values.");
205     }
207     if (!aValues.length) {
208       return Promise.resolve([]);
209     }
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);
220       }
221     }
223     for (let i = 0; i < aValues.length; i++) {
224       let index = 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);
230       } else {
231         // Given value is not a promise, forward it as a resolution value.
232         resolve(value);
233       }
234     }
236     return deferred.promise;
237   },
240 ////////////////////////////////////////////////////////////////////////////////
241 //// PromiseWalker
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.
250  */
251 this.PromiseWalker = {
252   /**
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.
256    */
257   handlers: [],
259   /**
260    * Called when a promise needs to change state to be resolved or rejected.
261    *
262    * @param aPromise
263    *        Promise that needs to change state.  If this is already resolved or
264    *        rejected, this method has no effect.
265    * @param aStatus
266    *        New desired status, either STATUS_RESOLVED or STATUS_REJECTED.
267    * @param aValue
268    *        Associated resolution value or rejection reason.
269    */
270   completePromise: function (aPromise, aStatus, aValue)
271   {
272     // Do nothing if the promise is already resolved or rejected.
273     if (aPromise[N_STATUS] != STATUS_PENDING) {
274       return;
275     }
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));
283       return;
284     }
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);
291     }
292   },
294   /**
295    * Sets up the PromiseWalker loop to start on the next tick of the event loop
296    */
297   scheduleWalkerLoop: function()
298   {
299     this.walkerLoopScheduled = true;
300     Services.tm.currentThread.dispatch(this.walkerLoop,
301                                        Ci.nsIThread.DISPATCH_NORMAL);
302   },
304   /**
305    * Schedules the resolution or rejection handlers registered on the provided
306    * promise for processing.
307    *
308    * @param aPromise
309    *        Resolved or rejected promise whose handlers should be processed.  It
310    *        is expected that this promise has at least one handler to process.
311    */
312   schedulePromise: function (aPromise)
313   {
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]);
318     }
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();
324     }
325   },
327   /**
328    * Indicates whether the walker loop is currently scheduled for execution on
329    * the next tick of the event loop.
330    */
331   walkerLoopScheduled: false,
333   /**
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.
337    *
338    * This function is called with "this" bound to the PromiseWalker object.
339    */
340   walkerLoop: function ()
341   {
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();
354     } else {
355       this.walkerLoopScheduled = false;
356     }
358     // Process all the known handlers eagerly.
359     while (this.handlers.length > 0) {
360       this.handlers.shift().process();
361     }
362   },
365 // Bind the function to the singleton once.
366 PromiseWalker.walkerLoop = PromiseWalker.walkerLoop.bind(PromiseWalker);
368 ////////////////////////////////////////////////////////////////////////////////
369 //// Deferred
372  * Returned by "Promise.defer" to provide a new promise along with methods to
373  * change its state.
374  */
375 function Deferred()
377   this.promise = new PromiseImpl();
378   this.resolve = this.resolve.bind(this);
379   this.reject = this.reject.bind(this);
381   Object.freeze(this);
384 Deferred.prototype = {
385   /**
386    * A newly created promise, initially in the pending state.
387    */
388   promise: null,
390   /**
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.
394    *
395    * This function is bound to its associated promise when "Promise.defer" is
396    * called, and can be called with any value of "this".
397    *
398    * @param aValue
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.
403    *
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.
407    */
408   resolve: function (aValue) {
409     PromiseWalker.completePromise(this.promise, STATUS_RESOLVED, aValue);
410   },
412   /**
413    * Rejects the associated promise with the specified reason.  If the promise
414    * has already been resolved or rejected, this method does nothing.
415    *
416    * This function is bound to its associated promise when "Promise.defer" is
417    * called, and can be called with any value of "this".
418    *
419    * @param aReason
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.
423    *
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.
428    */
429   reject: function (aReason) {
430     PromiseWalker.completePromise(this.promise, STATUS_REJECTED, aReason);
431   },
434 ////////////////////////////////////////////////////////////////////////////////
435 //// PromiseImpl
438  * The promise object implementation.  This includes the public "then" method,
439  * as well as private state properties.
440  */
441 function PromiseImpl()
443   /*
444    * Internal status of the promise.  This can be equal to STATUS_PENDING,
445    * STATUS_RESOLVED, or STATUS_REJECTED.
446    */
447   Object.defineProperty(this, N_STATUS, { value: STATUS_PENDING,
448                                           writable: true });
450   /*
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.
456    */
457   Object.defineProperty(this, N_VALUE, { writable: true });
459   /*
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.
462    */
463   Object.defineProperty(this, N_HANDLERS, { value: [] });
465   Object.seal(this);
468 PromiseImpl.prototype = {
469   /**
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.
473    *
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.
478    *
479    * @param aOnResolve
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.
486    *
487    * @param aOnReject
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
494    *        promise.
495    *
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.
506    *
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.
511    */
512   then: function (aOnResolve, aOnReject)
513   {
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);
521     }
523     return handler.nextPromise;
524   },
527 ////////////////////////////////////////////////////////////////////////////////
528 //// Handler
531  * Handler registered on a promise by the "then" function.
532  */
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 = {
542   /**
543    * Promise on which the "then" method was called.
544    */
545   thisPromise: null,
547   /**
548    * Unmodified resolution handler provided to the "then" method.
549    */
550   onResolve: null,
552   /**
553    * Unmodified rejection handler provided to the "then" method.
554    */
555   onReject: null,
557   /**
558    * New promise that will be returned by the "then" method.
559    */
560   nextPromise: null,
562   /**
563    * Called after thisPromise is resolved or rejected, invokes the appropriate
564    * callback and propagates the result to nextPromise.
565    */
566   process: function()
567   {
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];
572     try {
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);
579         }
580       } else if (typeof(this.onReject) == "function") {
581         nextValue = this.onReject(nextValue);
582         nextStatus = STATUS_RESOLVED;
583       }
584     } catch (ex) {
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") +
599              " callback.\n");
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");
603       }
605       // Additionally, reject the next promise.
606       nextStatus = STATUS_REJECTED;
607       nextValue = ex;
608     }
610     // Propagate the newly determined state to the next promise.
611     PromiseWalker.completePromise(this.nextPromise, nextStatus, nextValue);
612   },