UNPKG

@codelet/core

Version:
75 lines (74 loc) 2.6 kB
import { isPromiseLike } from '@daysnap/utils'; const NativePromise = globalThis.Promise; export function createUnhandledRejectionPromise(onError) { return class UnhandledRejectionPromise extends NativePromise { _handled = false; static get [Symbol.species]() { return NativePromise; } constructor(executor) { super((resolve, reject) => { let settled = false; const reportUnhandled = (reason) => { setTimeout(() => { if (!this._handled) { onError(reason); } }); }; const rejectWithReport = (reason) => { if (settled) return; settled = true; reject(reason); reportUnhandled(reason); }; const resolveWithThenable = (value) => { if (settled) return; let promiseLike = false; try { promiseLike = isPromiseLike(value); } catch (reason) { rejectWithReport(reason); return; } settled = true; if (promiseLike) { try { NativePromise.resolve(value).then(resolve, (reason) => { reject(reason); reportUnhandled(reason); }); } catch (reason) { reject(reason); reportUnhandled(reason); } return; } resolve(value); }; try { executor(resolveWithThenable, rejectWithReport); } catch (reason) { rejectWithReport(reason); } }); } then(onfulfilled, onrejected) { this._handled = true; return super.then(onfulfilled, onrejected); } catch(onrejected) { this._handled = true; return super.catch(onrejected); } finally(onfinally) { this._handled = true; return super.finally(onfinally); } }; }