[英]Remove event listener inside promise
我在 promise 中定义了一个事件监听器。 该代码有效,但我不知道如何删除事件侦听器。 在示例中,未使用 promise。 但是,我需要使用 promise 等待音频停止播放,然后再播放下一个音频。 我正在使用 react-native-sound-player。
这是我的代码:
const playSound = async url => {
try {
const sound = new Promise((resolve, reject) => {
SoundPlayer.addEventListener('FinishedPlaying', ({ success }) => {
console.log('finished playing', success)
resolve(success)
})});
SoundPlayer.playSoundFile(url, 'mp3');
await sound
SoundPlayer.stop()
} catch (e) {
console.log(`cannot play the sound file`, e);
}
};
这就是 package 示例删除 eventListener 的方式:
const playSound = url => {
try {
const sound = SoundPlayer.addEventListener('FinishedPlaying', ({ success }) => {
console.log('finished playing', success)
resolve(success)
})
SoundPlayer.playSoundFile(url, 'mp3');
SoundPlayer.stop()
sound.remove()
} catch (e) {
console.log(`cannot play the sound file`, e);
}
};
但这不适用于我的用例,因为我需要等待音频完成播放,然后才能进入下一个音频。 如何删除 eventListener?
通过传递对 function 的引用来设置事件处理程序。 然后只能通过传递完全相同的引用来删除它。 如果您使用匿名 function 设置了处理程序,那么根据定义,以后无法引用它。 只能删除命名函数。
示例:
function handler(){ console.log("you invoked the handler"); } document.getElementById("main").addEventListener("click", handler); document.getElementById("remove").addEventListener("click", function(){ document.getElementById("main").removeEventListener("click", handler); });
<button id="main">Click Me</button> <button id="remove">Remove Handler</button>
您的问题是您没有使用从.addEventListener
返回的内容。 根据文档,您需要使用返回的SubscriptionObject
来删除订阅。 尝试以下
const playSound = async (url) => {
try {
const promise = new Promise((resolve, reject) => {
const sound = SoundPlayer.addEventListener(
"FinishedPlaying",
({ success }) => resolve(sound)
);
});
SoundPlayer.playSoundFile(url, "mp3");
const sound = await promise;
SoundPlayer.stop();
sound.remove();
} catch (e) {
console.log(`cannot play the sound file`, e);
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.