Here is an example of promises in the context of a music computer game:
classMusicGame {// Public field currentSong =null;constructor() {this.audioElement =newAudio(); }// Public methodasyncplaySong(song) {console.log(`Playing song: ${song}`);try {// Load the song filethis.audioElement.src =`songs/${song}.mp3`;awaitthis.audioElement.play();// Update the current songthis.currentSong = song;console.log(`Finished playing: ${song}`); } catch (error) {console.error(`Error playing song: ${error}`); } }// Public methodasyncloadPlaylist(playlist) {console.log('Loading playlist...');try {// Load the playlist dataconstresponse=awaitfetch(`playlists/${playlist}.json`);constdata=awaitresponse.json();// Play the songs in the playlistfor (constsongofdata.songs) {awaitthis.playSong(song); }console.log('Playlist complete'); } catch (error) {console.error(`Error loading playlist: ${error}`); } }}constgame=newMusicGame();// This function call is asynchronousgame.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