Omar.Ebrahim
Omar.Ebrahim

Reputation: 874

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

Upvotes: 1

Views: 301

Answers (2)

jfriend00
jfriend00

Reputation: 707318

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

Upvotes: 2

ControlAltDel
ControlAltDel

Reputation: 35011

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

Upvotes: 0

Related Questions