Music Game Example

Here is an example of promises in the context of a music computer game:

class MusicGame {
  // Public field
  currentSong = null;

  constructor() {
    this.audioElement = new Audio();
  }

  // Public method
  async playSong(song) {
    console.log(`Playing song: ${song}`);

    try {
      // Load the song file
      this.audioElement.src = `songs/${song}.mp3`;
      await this.audioElement.play();

      // Update the current song
      this.currentSong = song;

      console.log(`Finished playing: ${song}`);
    } catch (error) {
      console.error(`Error playing song: ${error}`);
    }
  }

  // Public method
  async loadPlaylist(playlist) {
    console.log('Loading playlist...');

    try {
      // Load the playlist data
      const response = await fetch(`playlists/${playlist}.json`);
      const data = await response.json();

      // Play the songs in the playlist
      for (const song of data.songs) {
        await this.playSong(song);
      }

      console.log('Playlist complete');
    } catch (error) {
      console.error(`Error loading playlist: ${error}`);
    }
  }
}

const game = new MusicGame();

// This function call is asynchronous
game.loadPlaylist('pop');

console.log('Waiting for playlist to load...');

In this example, the MusicGame class has a playSong method that plays a song using an Audio element, and a loadPlaylist method that loads a playlist and plays all the songs in the playlist.

The playSong method uses the play method of the Audio element, which returns a promise that is fulfilled when the song has finished playing

Last updated