javascript - Prevent a promise from triggering a global 'unhandled rejection' event -


i'm writing library. @ 1 point create promise , swoop in later add then/catch handlers it. it's possible promise fail before i've attached error handler it. fine me; promise can exist in schrödingers-cat-like state until later maybe decide @ it.

the problem is, environments trigger global event if any promise gets rejected while has no error handler. maybe 1 of users has done drastic this in node:

process.on('unhandledrejection', function(reason){     console.error('oops', reason);     process.exit(1); }); 

i don't want rejected promise trigger if know i'm going go , check result later.

is there official way can mark promise exclude global 'unhandled rejection' event, or have synchronously attach error handler every promise avoid this?

file bug on environment (node). environment has no business acting on in way that's observable script.

in firefox , chrome there no script-observable consequences afaik.

even though chrome initally flag "unhandled promise rejection" in console, ✖ symbol, , calling error, backs off later if promise subsequently handled, changing ✖ ✓, , changing language "1 handled promise rejection".

firefox complain if unhandled promise rejection garbage collected.

a workaround might add hold function, like:

var hold = p => (p.catch(() => {}), p); 

then use silence node whenever know you'll promise later:

var console = { log: msg => div.innerhtml += msg + "<br>" };  window.onerror = () => console.log("window onerror fired");  var wait = ms => new promise(resolve => settimeout(resolve, ms));    var hold = p => (p.catch(() => {}), p);    var p = hold(promise.reject(new error("failure")));    wait(2000).then(() => p).catch(e => console.log(e.message + " handled."));
<div id="div"></div>


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -