Bug 1852754: part 9) Add tests for dynamically loading <link rel="prefetch"> elements...
[gecko.git] / toolkit / modules / PromiseUtils.sys.mjs
blobfa6b2aa4233f61b7e5199b9fda3a3bba48d73c2d
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this
3  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 export var PromiseUtils = {
6   /*
7    * Creates a new pending Promise and provide methods to resolve and reject this Promise.
8    *
9    * @return {Deferred} an object consisting of a pending Promise "promise"
10    * and methods "resolve" and "reject" to change its state.
11    */
12   defer() {
13     return new Deferred();
14   },
16   /**
17    * Requests idle dispatch to the main thread for the given callback,
18    * and returns a promise which resolves to the callback's return value
19    * when it has been executed.
20    *
21    * @param {function} callback
22    * @param {integer} [timeout]
23    *        An optional timeout, after which the callback will be
24    *        executed immediately if idle dispatch has not yet occurred.
25    *
26    * @returns {Promise}
27    */
28   idleDispatch(callback, timeout = 0) {
29     return new Promise((resolve, reject) => {
30       Services.tm.idleDispatchToMainThread(() => {
31         try {
32           resolve(callback());
33         } catch (e) {
34           reject(e);
35         }
36       }, timeout);
37     });
38   },
41 /**
42  * The definition of Deferred object which is returned by PromiseUtils.defer(),
43  * It contains a Promise and methods to resolve/reject it.
44  */
45 function Deferred() {
46   /* A method to resolve the associated Promise with the value passed.
47    * If the promise is already settled it does nothing.
48    *
49    * @param {anything} value : This value is used to resolve the promise
50    * If the value is a Promise then the associated promise assumes the state
51    * of Promise passed as value.
52    */
53   this.resolve = null;
55   /* A method to reject the assocaited Promise with the value passed.
56    * If the promise is already settled it does nothing.
57    *
58    * @param {anything} reason: The reason for the rejection of the Promise.
59    * Generally its an Error object. If however a Promise is passed, then the Promise
60    * itself will be the reason for rejection no matter the state of the Promise.
61    */
62   this.reject = null;
64   /* A newly created Pomise object.
65    * Initially in pending state.
66    */
67   this.promise = new Promise((resolve, reject) => {
68     this.resolve = resolve;
69     this.reject = reject;
70   });