How to deal with dangling promises

后端 未结 2 595
猫巷女王i
猫巷女王i 2021-01-03 05:28

Oftentimes I want to call a promise and just let it run asynchronously instead of waiting for it. Like:

... some code ...

fetchMyCount().then(count => {
         


        
相关标签:
2条回答
  • 2021-01-03 05:40

    Exactly for issues like this, I wrote my own utility for writing asynchronous code:

    https://github.com/vacuumlabs/yacol/

    It does not help you with your existing code, however with newly written code it provides (among many other things) quite advanced error-handling capabilities.

    This said, I don't think that "unhandledRejection" / "uncaughtException" events are good (although it's the best node.js natively provides) tools to do proper error handling:

    • First, you can only attach it process-wide, so it forces you to handle all uncaught errors the same way (unlike with try-catch where you can react differently to errors that originate from different parts of your code)

    • Second, "unhandledRejection" is called if .catch is not attached to the Promise in the same run of event loop. This may result in false errors being caught; note it is pretty OK to attach error handler to the promise later!

    0 讨论(0)
  • 2021-01-03 05:48

    This is a common use case. Your problem is real. In Node, you have process.on("unhandledRejection", ... events which you can use. Sadly, these are not available in browsers yet. Some libraries which are compatible with ES2015 promises offer them and you can use those until native promises get support.

    The upside is that support in browsers is coming and browsers will eventually support these hooks.

    Currently, I've convinced the polyfill to add it, so if you're using the core-js polyfill you can do:

    window.onunhandledrejection = function(e){
        // handle here e.promise e.reason
    };
    

    Note that this assumes that something is an unhandled rejection if: It's unhandled, and an error handler was not attached synchronously (within a task to be precise).

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