使用 Promise 和 await 而不是 then()

Using Promise and await instead of then()

我正在使用 MusicKit-JS,虽然这段代码可以工作,但我不知道是否有另一种编写方式。

音乐自成一体return__awaiter(...).

有没有办法用 promises 来写这个?我对它们了解不多,所以无法使用 promises 让它工作。

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

假设这些函数都是返回promise,你可以把它包装在一个async函数中然后使用await然后摆脱深层嵌套:

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

您需要做的就是将您的函数声明为异步。然后你就可以使用 await

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