Bug 1700051: part 13) Reduce accessibility of `mozInlineSpellStatus`'s constructor...
[gecko.git] / devtools / shared / async-utils.js
blob4d5ec336eb1920d37d985680ad613d251b00b9d1
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 "use strict";
7 /**
8  * Helpers for async functions. Async functions are generator functions that are
9  * run by Tasks. An async function returns a Promise for the resolution of the
10  * function. When the function returns, the promise is resolved with the
11  * returned value. If it throws the promise rejects with the thrown error.
12  *
13  * See Task documentation at https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Task.jsm.
14  */
16 /**
17  * Adds an event listener to the given element, and then removes its event
18  * listener once the event is called, returning the event object as a promise.
19  * @param  Element element
20  *         The DOM element to listen on
21  * @param  String event
22  *         The name of the event type to listen for
23  * @param  Boolean useCapture
24  *         Should we initiate the capture phase?
25  * @return Promise
26  *         The promise resolved with the event object when the event first
27  *         happens
28  */
29 exports.listenOnce = function listenOnce(element, event, useCapture) {
30   return new Promise(function(resolve, reject) {
31     const onEvent = function(ev) {
32       element.removeEventListener(event, onEvent, useCapture);
33       resolve(ev);
34     };
35     element.addEventListener(event, onEvent, useCapture);
36   });
39 // Return value when `safeAsyncMethod` catches an error.
40 const SWALLOWED_RET = Symbol("swallowed");
42 /**
43  * Wraps the provided async method in a try/catch block.
44  * If an error is caught while running the method, check the provided condition
45  * to decide whether the error should bubble or not.
46  *
47  * @param  {Function} asyncFn
48  *         The async method to wrap.
49  * @param  {Function} shouldSwallow
50  *         Function that will run when an error is caught. If it returns true,
51  *         the error will be swallowed. Otherwise, it will bubble up.
52  * @return {Function} The wrapped method.
53  */
54 exports.safeAsyncMethod = function(asyncFn, shouldSwallow) {
55   return async function(...args) {
56     try {
57       const ret = await asyncFn(...args);
58       return ret;
59     } catch (e) {
60       if (shouldSwallow()) {
61         console.warn("Async method failed in safeAsyncMethod", e);
62         return SWALLOWED_RET;
63       }
64       throw e;
65     }
66   };