1

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()
                    })
            })
    });
Omar.Ebrahim
  • 862
  • 1
  • 10
  • 30
  • [Aren't promises just callbacks?](https://stackoverflow.com/q/22539815) – VLAZ Aug 15 '21 at 17:35
  • 4
    it's already written using promises – Mechanic Aug 15 '21 at 17:39
  • Check the last code block in this answer for a way with await: https://stackoverflow.com/a/39458285/572644 – Daniel Hilgarth Aug 15 '21 at 17:39
  • 1
    It's not clear from your question: Is the code you've shown working and you just don't like the nesting? Or is the code you've shown *not* working? Separately: What's `__awaiter(...)`? The documentation should tell you. – T.J. Crowder Aug 15 '21 at 17:40
  • @T.J.Crowder Afaik, `__awaiter` is part of transpiled code, the classic coroutine runner to be used with promise-yielding generator functions, and probably won't be documented anywhere. – Bergi Aug 15 '21 at 17:52

2 Answers2

2

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);
});
jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

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()
                    })
            })
    });
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • What do you mean by "*declare your functions async*"? Why the plural? There's only one function in your code snippet. – Bergi Aug 15 '21 at 17:50