async-utils.js (2360B)
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/. */ 4 5 "use strict"; 6 7 /** 8 * Helpers for async functions. An async function returns a Promise for the 9 * resolution of the function. When the function returns, the promise is 10 * resolved with the returned value. If it throws the promise rejects with 11 * the thrown error. 12 */ 13 14 /** 15 * Adds an event listener to the given element, and then removes its event 16 * listener once the event is called, returning the event object as a promise. 17 * 18 * @param Element element 19 * The DOM element to listen on 20 * @param String event 21 * The name of the event type to listen for 22 * @param Boolean useCapture 23 * Should we initiate the capture phase? 24 * @return Promise 25 * The promise resolved with the event object when the event first 26 * happens 27 */ 28 exports.listenOnce = function listenOnce(element, event, useCapture) { 29 return new Promise(function (resolve) { 30 const onEvent = function (ev) { 31 element.removeEventListener(event, onEvent, useCapture); 32 resolve(ev); 33 }; 34 element.addEventListener(event, onEvent, useCapture); 35 }); 36 }; 37 38 // Return value when `safeAsyncMethod` catches an error. 39 const SWALLOWED_RET = Symbol("swallowed"); 40 41 /** 42 * Wraps the provided async method in a try/catch block. 43 * If an error is caught while running the method, check the provided condition 44 * to decide whether the error should bubble or not. 45 * 46 * @param {Function} asyncFn 47 * The async method to wrap. 48 * @param {Function} shouldSwallow 49 * Function that will run when an error is caught. If it returns true, 50 * the error will be swallowed. Otherwise, it will bubble up. 51 * @param {Mixed} retValue 52 * Optional value to return when an error is caught and is swallowed. 53 * @return {Function} The wrapped method. 54 */ 55 exports.safeAsyncMethod = function ( 56 asyncFn, 57 shouldSwallow, 58 retValue = SWALLOWED_RET 59 ) { 60 return async function (...args) { 61 try { 62 const ret = await asyncFn(...args); 63 return ret; 64 } catch (e) { 65 if (shouldSwallow()) { 66 console.warn("Async method failed in safeAsyncMethod", e); 67 return retValue; 68 } 69 throw e; 70 } 71 }; 72 };