@empathyco/x-components
Version:
Empathy X Components
45 lines (42 loc) • 1.65 kB
JavaScript
import { noOp } from './function.js';
/**
* Symbol used to know if a promise is cancelled.
*
* @internal
*/
const CancelSymbol = Symbol('cancelled-promise');
/**
* Util function that returns an object which contains a promise, result of Promise.race call
* between the original one passed as parameter and another one, created within the function, used
* for reject in the resultant promise manually. If the cancel method is triggered, the
* resultant promise is rejected.
*
* @remarks The promise function passed as first param executes its own async code ALWAYS although
* it's cancelled or not. The payload of the resultant promise is the returned by the function that
* ends first. So, the promise is not cancelled exactly. The parameter first passed to cancel is the
* resultant promise rejection value.
*
* If you need to check if the promise is not being rejected with CancelSymbol (on purpose).
* You should check the error type in the cancellable catch using the payload.
*
* @param promise - Original promise.
* @param cancelCallback - Optional callback to be called on cancel.
* @returns CancellablePromiseFunction {@link CancellablePromiseFunction}.
*
* @internal
*/
function cancellablePromise(promise, cancelCallback) {
let cancel = noOp;
const cancelPromise = new Promise((_, reject) => {
cancel = payload => {
reject(CancelSymbol);
cancelCallback?.(payload);
};
});
return {
promise: Promise.race([promise, cancelPromise]),
cancel,
};
}
export { CancelSymbol, cancellablePromise };
//# sourceMappingURL=cancellable-promise.js.map