Search code examples
typescriptasynchronouses6-promise

Typescript async method declaration


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


Solution

  • 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.