【问题标题】:Escape multiple nested functions in NodeJS在 NodeJS 中转义多个嵌套函数
【发布时间】:2020-01-12 22:08:45
【问题描述】:

我的 Javascript 代码如下所示:

function someFunction() {
    // Code
    somePromise().catch(err => {
        console.log(err);
    });
    // Mode Code
}

如果somePromise() 被拒绝,我想同时转义somePromise().catchsomeFunction()。我尝试使用return,但这只能让我逃脱somePromise().catch。是否有任何函数可以让我跳出嵌套循环?

【问题讨论】:

  • 不抓住 somePromise 怎么样? (删除 .catch())
  • 很遗憾,这不是我可以使用的选项。

标签: javascript node.js promise es6-promise


【解决方案1】:

您可以使用async/await

function async someFunction() {
    // Code
    try {
        await somePromise();
    } catch (err) {
        console.log(err);
        return; // aborts further execution
    }
    // More Code
}

详情请见async function

【讨论】:

    【解决方案2】:

    Async/await 可以解决问题,但重要的是要了解它为什么会解决问题。

    Promise 是一种存储延续的机制。传递给 thencatch 的函数存储在 Promise 中,并在 Promise 解决时执行。

    要在不使用async/await 的情况下解决此问题,您只需返回 Promise 并使用 then 执行任何应在 Promise 不拒绝时执行的代码:

    function someFunction() {
        // Code
        return somePromise()
          .then(result => {
            // More Code
          })
          .catch(err => {
            console.log(err);
          });
    }
    

    这基本上就是async/await 去糖的目的。 Async/await 是围绕状态机的语法糖,它为您连接这些延续。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-16
      • 2016-03-20
      相关资源
      最近更新 更多