gpt4 book ai didi

javascript - 如何使用 Promise 重试在 TypeScript 中加载 MediaElement?

转载 作者:行者123 更新时间:2023-12-03 00:56:09 27 4
gpt4 key购买 nike

我正在尝试实现一些重试逻辑来处理 <audio /> 的情况元素在 TypeScript React 中遇到网络错误 ( HTMLMediaElement.error )。到目前为止,我进行了基本的重试,更新了 src在音频元素上,这似乎迫使它重新获取。

我已经尝试让 Promise 工作几个小时,但我正在努力将在线通用示例(通常在 JavaScript 中)映射到我在 TypeScript 中的特定实现。

这是我迄今为止所掌握的相关代码:

private element: HTMLAudioElement | null = null;    

public componentDidMount() {
if (this.element !== null) {
this.element.addEventListener("error", this.retry, false);
}
}

private readonly retry = () => {
if (this.element !== null && this.element.error !== null) {
if (this.element.error.code === 2 && this.props.src !== undefined) {
this.element.src = this.props.src;
}
}
};

public render() {
const { src } = this.props;
return (
<audio ref={ref => (this.element = ref)} src={src} />
);
}

如何使用基于 Promise 的 TypeScript 解决方案(具有定时最大重试次数)替换此代码,例如重试 3 次,每次间隔 5 秒?

最佳答案

也许您可以跟踪加载错误的数量来满足您的要求,并进行以下更改:

private element: HTMLAudioElement | null = null;    
private loadAttempts: number = 0;

public componentDidMount() {
if (this.element !== null) {
this.element.addEventListener("error", this.retry, false);
}
}

private readonly retry = () => {

if(this.loadAttempts >= 2) {
return;
}

if (this.element !== null && this.element.error !== null) {
if (this.element.error.code === 2 && this.props.src !== undefined) {

// Wait for 5 seconds before attempting another reload
setTimeout(() => {

this.element.src = this.props.src;
this.element.load(); // Best pratice
this.loadAttempts ++;

}, 5000) // Delay for 5 seconds before attempted retry
}
}
};

public render() {
const { src } = this.props;
return (
<audio ref={ref => (this.element = ref)} src={src} />
);
}

关于javascript - 如何使用 Promise 重试在 TypeScript 中加载 MediaElement?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52832041/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com