首页 > 解决方案 > 我收到“主线程上的同步 XMLHttpRequest”错误,但我的代码按预期工作

问题描述

这是我的一段代码,用于确保给定 URL 中是否有文件。

如果有基于该文件 URL 的文件,我们console.log('We have context for the question');console.log('No available context');

代码按预期工作,但控制台中出现错误:

speak('note');

function contextExist(url) {

    return new Promise((resolve) => {   

        const xhr = new XMLHttpRequest();
        xhr.open('HEAD', url, false);
        xhr.send();
        return resolve(xhr.status==200);  

    });

}


// Speak Module
async function speak(type) {
  
    switch (type) {
               
       case 'note':
       let resolved = await contextExist('https://round-arm-authority.000webhostapp.com/Ultimate%20Video%20Hack/videos/vid1.mp4');
      
       if(resolved === true){
         console.log('We have context for the question'); 
    
       } else {
         console.log('No available context'); 
  
       }

       break;
  }

}

每次我在控制台中收到此错误时:

在此处输入图像描述

因为我的代码工作正常,我想知道这是否是一个严重的错误?我该如何解决这个错误?

更新:

speak('note');

function contextExist(url) {

    return new Promise((resolve) => {   

        const xhr = new XMLHttpRequest();
        xhr.open('HEAD', url, true);

        xhr.onload = function (e) {
        return resolve(xhr.status==200)
        };
        xhr.onerror = function (e) {
         return resolve(xhr.status==200)
      };

        xhr.send();
         
    });

}


// Speak Module
async function speak(type) {
  
    switch (type) {
               
       case 'note':
       let resolved = await contextExist('https://round-arm-authority.000webhostapp.com/Ultimate%20Video%20Hack/videos/vid1.mp4');
      
       if(resolved === true){
         console.log('We have context for the question'); 
    
       } else {
         console.log('No available context'); 
  
       }

       break;
  }

}

标签: javascript

解决方案


推荐阅读