2016-08-30 55 views
0

我使用的聲音播放器名爲IonSound.js,可以在此處找到。 http://ionden.com/a/plugins/ion.sound/en.html在外部事件事件中觸發Promise.fulfill

根據該文件,我可以聽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

問題是,它變得像這樣一團糟。我想要做的卻是promisifying我的聲音類,所以我可以用它像這樣:

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

爲了做到這一點,這段代碼有fulfill()我的承諾,我一直在this.promises哈希值。

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

,但它並沒有任何方法來觸發履行這樣的:

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

任何想法?

回答

3

而不是在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; 
     } 
    } 
} 
+0

你太了不起了。上帝保佑你的公爵! – Aris