2016-08-30 2 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."); 
}); 

을 그렇게하기 위해서는,이 코드 조각은 내가 this.promises 해시에 보관 내 약속을 fulfill()한다.

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

관련 문제