Drex
Drex

Reputation: 3851

async method declaration without `function` keyword in side javascript class

Recently I've seen some code example with javascript class, when declaring an async method, it does not contain the function keyword, nor it's using an arrow function as usual, code example

export default class CartClient {
   async getCart(authToken, cartId) {
    const request = this.request
      .url(`${this.url}/${cartId}`)
      .get()
      .auth(authToken)
      .withNoCache()
      .build();
    const response = await fetch(request);

    return await response.json();
  }
}

This is the very first time I've seen things like this, usually I was told to create function using function keyword or arrow function like below

async function getCart() {
   // implementation
}
or
async getCart = () => {
   // implementation
}

Could anyone let me know why we don't need the function keyword anymore when declaring the method? Is it a javascript related feature or react feature? Since I've seen in a react project.

Upvotes: 0

Views: 588

Answers (1)

Evert
Evert

Reputation: 99687

Methods in classes do not have the function prefix. In fact, they are disallowed.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

Upvotes: 3

Related Questions