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?

0

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

Main one being async arrow functions don't carry over context from a construction, this refers to Window.
@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
@BrettReinhard Take a look at this: stackoverflow.com/questions/22939130/…
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.