【问题标题】:How to solve Uncaught (in promise) DOMException error?如何解决 Uncaught (in promise) DOMException 错误?
【发布时间】:2019-04-04 19:13:54
【问题描述】:

我在 HTML 中使用两个视频标签来加载当前视频以及下一个视频。随着当前视频开始播放,下一个视频将被隐藏并预加载。 当前视频结束时,它将淡出,而下一个视频将淡入。这两个视频标签将以奇特的方式工作,以在更改视频源的同时播放即将播放的视频。

问题 当用户连续点击更改视频时,控制台会返回一个 Uncaught (in promise) DOMException 错误,它指向正在更改视频源的代码。

该错误可能是由于视频源不断更改,因为在更改之前已经在该源中播放了视频。 另一方面,每次点击都会创建一个视频播放承诺请求,该请求可能会因为连续点击而被中断,因为请求在解决之前就被中断了。

我已尝试通过空字符串清除两个视频源,但仍会生成错误。

    // video source is getting changed which interrupts the promise and the error pointer
    oppositeVideoElement.pause();
    $(oppositeVideoElement).fadeOut(800, function () {
        $(oppositeVideoElement).attr('src', nextVideoSource); // line where error points
    });

// Play promise code which gets interrupted before resolve
function playPromiseForMobileVideo(videoElement, videoAboutToPlay) {
    var playPromise = videoElement.play();
    if (playPromise !== undefined) {
        console.log(playPromise);
        playPromise.then(
            function () {
                if (currentDevice == 'mobile' && mobileFirstTime) {
                    videoElement.pause();
                    mobileFirstTime = false;
                }
            }).catch(function (e) {
                if(cameFromNetwork) {
                    videoElement.load();
                    videoElement.play();
                    cameFromNetwork = false;
                    return;
                }
                videoElement.pause();
                $(videoElement).attr('src', videoAboutToPlay);
                videoElement.load();
                videoElement.play();
                console.log('catch video Element', videoElement);
            });
    }
}

预期结果:错误应该被删除,卡住的承诺应该被杀死。

实际结果:产生了阻止当前视频播放的错误。

【问题讨论】:

  • 在promise“链”中添加一个catch来捕获错误。
  • @Jite 我已经有了catch块,但是代码没有执行或进入catch块。它只指向视频源发生变化的代码。

标签: javascript jquery promise html5-video es6-promise


【解决方案1】:

promise 是一种预期会被解决或被拒绝的结构。当您使用 Promise 时,您必须同时处理两者,也就是说,您必须为拒绝创建一个句柄,就像您必须为解析创建一个句柄一样。

当调用一个方法作为一个promise时,你应该总是在最后添加一个.catch()catch调用需要一个回调,它将传递一个错误作为参数。

例子:

const method = () => {
  return new Promise((resolve, reject) => {
    reject(new Error({});
  }); 

}

method.then(...).catch(e => console.err(e.message));

如果 promise 失败,你必须捕获错误。

如果您使用 async/await,则使用 try/catch 代替:

try {
  await method();
} catch (e) {
  console.error(e.message);
}

【讨论】:

    猜你喜欢
    • 2018-01-27
    • 1970-01-01
    • 2020-09-27
    • 1970-01-01
    • 2021-11-05
    • 2021-04-28
    • 1970-01-01
    • 2021-05-21
    • 2018-09-02
    相关资源
    最近更新 更多