Uncaught (in promise) Error

前端 未结 1 1592
陌清茗
陌清茗 2020-12-18 10:05

This is obviously a SSCCE. I have the following (jsFiddle here):


  
    
    
相关标签:
1条回答
  • 2020-12-18 10:19

    It's not an uncaught exception, it's an uncaught rejection. Promises should not be left dangling in the rejected state with no error callback attached - that's why the console is warning you about this. You can also handle these cases in your application with the unhandledrejection event.

    If you want to handle the error later (install the handler when the user clicks the button, which might be never!), you still will need to immediately install an empty callback (that explicitly ignores the error) to suppress the warning.

    var p = Promise.resolve();
    document.getElementById('file-dlg').addEventListener('change', function createPromise() {
      p = new Promise(function executor(resolve, reject) {
        throw new Error('snafu');
      });
      p.catch(e => {/* ignore for now */});
    });
    document.getElementById('submit').addEventListener('click', function addErrorHandler() {
      p.catch(function onReject(e) {
        console.error('some problem happened', e);
      });
    });
    

    Notice that you don't need that try/catch - the promise constructor will catch all exceptions from the executor by default already.

    0 讨论(0)
提交回复
热议问题