Using Promise and await instead of then()

298 views Asked by At

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()
                    })
            })
    });
2

There are 2 answers

0
jfriend00 On BEST ANSWER

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);
});
1
ControlAltDel On

All you need to do is declare your functions async. Then you will be able to use await

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