peter
Version:
Peter Test Framework
41 lines (35 loc) • 833 B
JavaScript
/**
* @file src/utils/defer-promise.js
* @author Ryan Rossiter, ryan@kingsds.network
* @date July 2020
*
* This utility function will wrap a promise to prevent it from
* throwing an UnhandledPromiseRejectionWarning, and return a function
* so that the promise can be handled later.
*/
/**
* @template T
* @callback DeferPromiseCallback
* @returns {Promise<T>}
*/
/**
* @template T
* @param {Promise<T>} promise
* @returns {DeferPromiseCallback<T>}
*/
module.exports = function deferPromise(promise) {
let threw = false;
let result = undefined;
let handledPromise = promise.then(
(res) => (result = res),
(err) => {
threw = true;
result = err;
}
);
return async () => {
await handledPromise;
if (threw) throw result;
else return result;
}
}