In Node.js 7 what is the proper way to suppress UnhandledPromiseRejectionWarning?

后端 未结 4 916
谎友^
谎友^ 2021-01-04 10:26

In Node.js I have a module which consists of just one function. The function returns promise and the promise could be rejected. Still I don\'t want to force all users of the

4条回答
  •  离开以前
    2021-01-04 10:41

    In general, using a custom library like bluebird you can suppress rejections just from your code but nowhere else. Native promises can't do this yet.

    You can however manually suppress a promise by adding a catch handler for it.

     function yourExportedFunction() {
         const p = promiseThatMightRejectFn(); 
         p.catch(() => {}); // add an empty catch handler
         return p;
     }
    

    This way you are explicitly ignoring the rejection from the promise so it is no longer an unhandled rejection just a suppressed one.

提交回复
热议问题