1

What is the difference between :

public myFunction = async (
    req: Request, 
    res: Response
): Promise<Response> => {
    return await myOtherFunction() 
}

and

public async myFunction (
    req: Request, 
    res: Response
): Promise<Response> {
   return await myOtherFunction()
}

I mostly use the first exemple, but when converting a function that is not async, my code editor (vs code) uses the second exemple.

Probably not relevant but I am using typescript 3.1.3

1 Answer 1

1

First one is an arrow function and second one is called normal function.

Main difference is that arrow functions this refers to an parent object/class and normal functions this refers to an function itself. If you would use arrow function in node and use it on top level it would refer to undefined.

reference code, heres little reference code which is made in React.js, just to demonstrate the use case.

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

6 Comments

According to your links, the first one is a normal function and the second one is an arrow function no ?
My bad I miss spelled it. It is actually other way around, I fix it to the answer. Good notice!
Thank you very much, I didn't quite get the difference (not using the this keyword a lot) but your answer totally explains what I was wondering about
Just to make things more clear I also added example of top level arrow function to codesandbox example.
Some frameworks like React.js uses this-keyword a lot so you'll get use to them if you get into one of these frameworks. Otherwise it doesn't affect too much which of these functions you are using.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.