Course contentsShow
← JavaScript
Lesson 1336 of 2,72330. Async/AwaitFree lesson

Async Methods in Objects and Classes

Define async methods using shorthand syntax in object literals and class definitions.

Async Methods in Objects and Classes

You'll learn how to define async methods directly inside object literals and ES6 classes using concise syntax.

The Core Idea

Just like you can define regular methods with shorthand syntax in objects and classes, you can also define async methods. Simply add the async keyword before the method name. These methods automatically return promises and can use await internally, making them perfect for organizing asynchronous logic within your data structures and class instances.

Async Methods in Object Literals

const user = {
  name: 'Alice',
  
  async fetchProfile() {
    // This method returns a promise
    return { id: 123, bio: 'Developer' };
  },
  
  async updateSettings(newSettings) {
    // Can use await inside
    const profile = await this.fetchProfile();
    return { ...profile, settings: newSettings };
  }
};

// Calling async methods
user.fetchProfile().then(profile => console.log(profile));

Async Methods in Classes

class DataService {
  constructor(apiUrl) {
    this.apiUrl = apiUrl;
  }
  
  async loadData() {
    // Async instance method
    return { data: 'example' };
  }
  
  async saveData(data) {
    const current = await this.loadData();
    return { ...current, ...data };
  }
  
  static async initialize() {
    // Async static method
    return new DataService('https://api.example.com');
  }
}

const service = new DataService('url');
service.loadData().then(data => console.log(data));

Think of it this way: You're giving your objects and classes the ability to perform time-consuming operations (like API calls) as naturally as they handle regular methods, without cluttering your code with manual promise construction.

Key Takeaway: Use async before method names in objects and classes to create methods that automatically return promises and support await, keeping asynchronous logic cleanly organized within your data structures.