你如何创build一个命名的asynchronous箭头function?
目前,我有这样的代码:
async function getConnection(){ // logic here... }
为了使其与我的代码库的其余部分保持一致,我想将其更改为箭头函数。 我试过async getConnection () => { ... }
但似乎没有工作。 什么是正确的方法来做到这一点?
箭头函数没有名字,但你可以将它们分配给一个像这样的variables:
const normalFunc = () => { ... }; const asyncFunc = async () => { ... };
但是,请注意,箭头函数不仅仅是常规函数的简短表示法,因为需要注意一些细微的差异( 请参阅本文中的详细信息 )。 但是,如果您了解这些差异并且不影响您的代码,则应该没问题。
箭头函数不能有一个名字
const getConnection = async () => {}
但是将所有函数简单地replace为箭头函数是非常愚蠢的,并且可能容易出错。 在这样做之前了解所有的差异 。
箭头函数不能用名称声明,但可以分配。
试试:
var getConnection = async () => { return 'It works'; } getConnection().then(message => console.log(message))
希望这可以帮助