我正在使用名为 IonSound.js
的声音播放器,可以在此处找到它。 http://ionden.com/a/plugins/ion.sound/en.html
根据文档,我可以像这样监听 sound.ending
事件:
ion.sound({
sounds: [
{name: "door_bump"},
{name: "water_droplet_2"},
{name: "water_droplet_3"}
],
ended_callback: function (sound) {
// sound ended
game.sound.soundEnded(sound);
}
});
我在此之上制作了一个非常基本的包装器。
class Sound
{
constructor(ion) {
this.ion = ion;
this.promises = {};
}
play(sound) {
if (game.settings.muted === false) {
this.ion.sound.play(sound);
}
this.promises[sound] = new Promise((accept, reject) => {
});
return this.promises[sound];
}
soundEnded(sound) {
if (this.events.hasOwnProperty(sound.name) === true) {
Promise.resolve(this.promises[sound.name])
}
}
}
现在,当我执行以下代码时:
game.sound.play("level-up");
ending_callback
触发器。然后它调用 sound.soundEnded
。
问题是,事情变得一团糟。我想做的是 promise 我的 Sound 类,这样我就可以像这样使用它:
game.sound.play("level-up").then(() => {
console.log("Sound is over.");
});
为了做到这一点,这段代码必须fulfill()
我在this.promises
哈希上保留的 promise 。
Promise.resolve(this.promises[sound.name]);
但它没有任何方法来触发执行,如下所示:
this.promises[sound.name].fulfill();
有什么想法吗?
最佳答案
不要在 this.promises
中保留一组 Promise,而是在 this.promiseFulfil
中保留一组 Promise 接受/拒绝回调。这样你就可以实现 promise 。
以下是您的类的外观:
class Sound
{
constructor(ion) {
this.ion = ion;
this.promiseFulfil = {};
}
play(sound) {
if (game.settings.muted === false) {
this.ion.sound.play(sound);
}
// Just return the promise without storing it.
return new Promise((accept, reject) => {
// keep track of which function to call to fulfil promise:
this.promiseFulfil[sound] = { accept, reject };
});
}
soundEnded(sound) {
if (this.promiseFulfil[sound]) {
// call the appropriate promise-callback:
this.promiseFulfil[sound].accept();
// optionally clear this entry:
this.promiseFulfil[sound] = undefined;
}
}
}
关于javascript - 在外部范围事件上触发 Promise.fulfill,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39227851/