【问题标题】:How do you create a named async arrow function? [duplicate]你如何创建一个命名的异步箭头函数? [复制]
【发布时间】:2018-01-14 08:03:15
【问题描述】:

目前,我有这个代码:

async function getConnection(){
    // logic here...
}

为了使其与我的代码库的其余部分保持一致,我想将其更改为箭头函数。我试过async getConnection () => { ... } 但这似乎不起作用。正确的做法是什么?

【问题讨论】:

    标签: javascript node.js arrow-functions ecmascript-2017


    【解决方案1】:

    箭头函数没有名称,但您可以将它们分配给这样的变量:

    const normalFunc = () => { ... };
    const asyncFunc  = async () => { ... };
    

    但是请注意,箭头函数不仅仅是常规函数的较短符号,因为有一些细微的差异需要注意 (see this article for details)。但是,如果您了解这些差异并且它们不会影响您的代码,那么您应该没问题。

    【讨论】:

      【解决方案2】:

      箭头函数不能有名字

      const getConnection = async () => {}
      

      但是将所有函数简单地替换为箭头函数简直是愚蠢的,并且可能容易出错。在这样做之前Learn all differences

      【讨论】:

      • 主要的异步箭头函数不会从构造中继承上下文,this 指的是Window
      • @Crowes 我认为更清楚一点,this 将引用箭头函数在其中声明的任何函数或对象的this。我假设将在全局范围,所以你是正确的
      • @BrettReinhard 看看这个:stackoverflow.com/questions/22939130/…
      【解决方案3】:

      箭头函数不能用名称声明,但可以赋值。

      试试:

      var getConnection = async () => {
        return 'It works';
      }
      
      getConnection().then(message => console.log(message))
      

      希望对你有帮助

      【讨论】:

        猜你喜欢
        • 2019-03-11
        • 2019-09-04
        • 2020-05-29
        • 2017-08-15
        • 1970-01-01
        • 2019-08-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多