【问题标题】:Triggering Promise.fulfill on an outer-scope event在外部范围事件上触发 Promise.fulfill
【发布时间】:2016-08-30 12:42:24
【问题描述】:

我正在使用一个名为IonSound.js 的声音播放器,可以在此处找到它。 http://ionden.com/a/plugins/ion.sound/en.html

根据文档,我可以像这样监听sound.ended 事件:

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

ended_callback 触发器。然后它调用sound.soundEnded。

问题是,它变得像这样一团糟。我想做的是承诺我的 Sound 类,这样我就可以像这样使用它:

game.sound.play("level-up").then(() => {
    console.log("Sound is over.");
});

为了做到这一点,这段代码必须fulfill()我的Promise,我保留在this.promises哈希上。

Promise.resolve(this.promises[sound.name]);

但它没有任何方法可以像这样触发完成:

this.promises[sound.name].fulfill();

有什么想法吗?

【问题讨论】:

    标签: javascript node.js promise callback dom-events


    【解决方案1】:

    不要在this.promises 中保留一组承诺,而是在this.promiseFulfil 中保留一组承诺接受/拒绝回调。这样你就有了实现承诺的句柄。

    这是你的班级的样子:

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

    【讨论】:

    • 你太棒了。上帝保佑你的总督!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-14
    相关资源
    最近更新 更多