DEV Community


Posted on

async-await in Javascript class

One of the projects that I am working on recently has to use async methods and also call it from another method of the same class. Thought of writing this as it may help others

It's actually pretty simple. You can invoke the async method from another method by using an immediately invoking function.
Let's see it with an example. I have a class Todo, its constructor invokes an async method

class Todo {
    constructor() {
        this.apiUri = 'https://someapiuri';
        (async () => await this.getTodoItems())();

    async getTodoItems() {
        const response = await fetch(this.apiUri);
        return await response.json();

Enter fullscreen mode Exit fullscreen mode

Top comments (0)