How to deal with dangling promises

后端 未结 2 597
猫巷女王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!

提交回复
热议问题