Search code examples
javascriptasync-awaitpromiseapple-musickit-js

Using Promise and await instead of then()


I'm using MusicKit-JS and while this code works I don't know if there's another way of writing it.

The music methods themselves all return __awaiter(...).

Is there a way to write this using promises? I don't know much about them so couldn't get it working using promises.

music.stop()
    .then(function () {
        music.setQueue({})
            .then(function () {
                music.setQueue({ song: id })
                    .then(function () {
                        music.play()
                    })
            })
    });

Solution

  • Assuming these functions are all returning promises, you can wrap it in an async function and then use await and then get rid of the deep nesting:

    async function run() {
        await music.stop();
        await music.setQueue({});
        await music.setQueue({song: id});
        await music.play();
    }
    
    run().then(() => {
        console.log("done");
    }).catch(err => {
        console.log(err);
    });