javascript - 在nodejs中等待promise时捕获异常

标签 javascript node.js error-handling promise throw

我正在用nodejs编写一个库,它包装了另一个库。我的代码是这样的:

function wrapper(functionToWrap) {
    return function(param1, param2) {
        try {
             return functionToWrap(param1, param2);
        } catch(err) {
            console.log(err);
            throw err;
        } finally {
            finalizeWrapping();
        }
    }
}

问题是我的 finalizeWrapping 函数是一个等待我收集的 promise (通过在它使用的某些异步 api 上调用 functionToWrap 之前放置一些钩子(Hook))来解析的函数,然后才执行操作,如下所示:

function finalizeWrapping() {
    Promise.all(pendingPromises).then(function(values) {
        //finalize the wrapping
        console.log('all promises fulfilled!');
    });
}

问题在于,在解决所有 Promise 并执行 then block 之前,会引发错误并退出 Node (不应处理此错误,因为包装的函数不会处理它)。

我的问题是:我可以做些什么来解决这个问题,这意味着适本地向用户抛出错误完成执行 then block ,或者我是否必须更改 Hook api 的方式以同步而不使用 promise ?

提前感谢所有帮助者:)

编辑:试图让我的问题更清楚 - functionToWrap 不是我的函数,它是不同库的函数(并且它可以更改 - 这意味着我希望我的代码能够包装尽可能多的函数)。这个函数允许使用异步api(我可能正在尝试monkeypatch),基本上它应该有尽可能少的限制 - 我希望用户能够编写任何函数并且我能够包装它。

最佳答案

不确定以下内容是否有帮助,尽管我认为您可以对自己的问题及其答案发表评论,但您可能没有足够的声誉来发表评论。

const wrapper = functionToWrap => 
  function() {
      //special type to indicate failed call to functionToWrap
      const Fail = function(reason){this.reason=reason;};
      //does not matter how many argument. Assuming functionToWrap
      //  does not rely on "this". If it does then also pass the 
      //  object that functionToWrap is on and replace null with that object
      return Promise.resolve(Array.from(arguments))
      .then(
        //if functionToWrap is on an object pass it to wrapper
        // and replace null with that object
        args=>functionToWrap.apply(null,args)
      )
      .catch(
        //if functionToWrap throws an error or rejects we will catch it here
        //  and resolve with a special Fail type value
        err=>{
          console.log(err);
          return new Fail(err)          
        }
      ).then(
        //since promise cannot fail (its rejection is caught and resolves with Fail)
        //  this will always be called
        //finalize should return Promise.all... and maybe not use a shared
        //  variable called pendingPromises, global shared mutable variables in async 
        //  functions is asking for trouble
        result=>finalizeWrapping().then(
          ()=>
            //if functionToWrap rejected or thew the result will be a Fail type
            (result && result.constructor === Fail)
              ? Promise.reject(result.reason)//reject with the original error
              : result//resolve with the functionToWrap result
        )
      );
  }

关于javascript - 在nodejs中等待promise时捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48784302/

相关文章:

java - 如何在ANTLR4中实现错误处理

发生 fatal error 时php重新加载页面

javascript - 使用 jquery/javascript 使用正则表达式解析文本

javascript - 打印的字符串显示为未定义

javascript - 从另一个文件进行 module.export-ing 后,函数未定义

node.js - 在 express js 中请求同一服务器上的端点

node.js - PM2环境变量缓存

javascript - 如何将Json数据转换为EXTJS中的变量

javascript - 使用范围 : $scope 时,ngDialog $scope 变量未被 $dialog 中的 ngModel 字段更新

c - C 编程中字符数据类型的错误处理