4

Currently, I have this code:

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

To make it consistent with the rest of my codebase, I want to change it to an arrow function. I've tried async getConnection () => { ... } but that didn't seem to work. What would be the correct way to do it?

Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072
ifvictr
  • 131
  • 1
  • 2
  • 13

3 Answers3

4

Arrow functions have no name, but you can assign them to a variable like this:

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

Do note, however, that arrow functions are not just shorter notation for regular functions, as there are some subtle differences to be aware of (see this article for details). However, if you understand these differences and they don't affect your code, you should be fine.

Frxstrem
  • 30,162
  • 8
  • 66
  • 99
1

Arrow functions can't have a name

const getConnection = async () => {}

But simple replace of all functions to arrow functions is simply stupid and in might be error-prone. Learn all differences before doing so.

wookieb
  • 2,836
  • 1
  • 11
  • 13
  • Main one being async arrow functions don't carry over context from a construction, `this` refers to `Window`. – Crowes Aug 07 '17 at 08:04
  • 1
    @Crowes I think to be more clear, `this` will refer to the `this` of whatever function or object the arrow function was declared in. I'm assuming a const would be declared on the global scope so you are correct – Brett Reinhard Aug 08 '17 at 17:01
  • @BrettReinhard Take a look at this: https://stackoverflow.com/questions/22939130/when-should-i-use-arrow-functions-in-ecmascript-6?answertab=votes#tab-top – Crowes Aug 08 '17 at 20:59
1

An arrow function can't be declared with a name, but can be assigned.

Try :

var getConnection = async () => {
  return 'It works';
}

getConnection().then(message => console.log(message))

Hope this helps

KpTheConstructor
  • 2,579
  • 1
  • 11
  • 18