Home > Back-end >  How do catch a reject from a function which contains a promise but does not return it
How do catch a reject from a function which contains a promise but does not return it

Time:06-23

I have a function main which contains a promise but does not return one. Something like this.

function main() {
  var prom = new Promise(function(resolve, reject) {
    setTimeout(() => {
      console.log("testing");
      reject();
    }, 2000);
  });

  return "success";
}

main();

When I run the code, it gives an Uncaught (in promise) DOMException and stops the javascript code. I can't modify the main function at all. How can I catch the rejection?

CodePudding user response:

You can listen for the "unhandledrejection" event.

window.addEventListener("unhandledrejection", e => {
    e.preventDefault(); // prevent error message
    // handle...
    // e.promise is the Promise that was rejected
    // e.reason is the object passed to reject()
});
  • Related