首页 > 解决方案 > 为什么我的网站在每个文件都成功加载后显示加载图标?

问题描述

所以我在学习 JavaScript Promises 并创建了一个网页,显示从目录中的另一个文件派生的文本。它成功加载了站点和所有内容,但问题是即使在站点加载并从其他网页访问数据之后,它仍显示加载图标。我尝试从文件中删除承诺,当我再次访问该网页时,没有加载图标。所以我认为诺言有问题。

function myDisplayer(some) {
  document.write(some);
}
async function loadController(){
    let myPromise = new Promise(function(myResolve, myReject) {
      let req = new XMLHttpRequest();
      req.open('GET', "controllerDummy.html");
      req.onload = function() {
        if (req.status == 200) {
          myResolve(req.response);
        } else {
          myReject("File not Found");
        }
      };
      req.send();
    });
    myDisplayer(await myPromise);
}

loadController()
<!DOCTYPE html>
<html style="background-color: black;">
<head>
    <script type="text/javascript" src="controller.js"></script>
</head>
<body>
    
</body>
</html>
<!DOCTYPE html>
<html style="background-color: black;">
    <body>Loading Controller</body>
</html>

这些是所有文件,现在是屏幕截图。网页,衍生文本是黑色的,背景也是黑色的,因为我不喜欢白色的网站和白色的UI设计

如您所见,promise 已加载,但站点仍在加载图标。有什么解决办法吗?这种方式是过时的还是什么?

标签: javascripthtmlasynchronousxmlhttprequestes6-promise

解决方案


兑现承诺

function myDisplayer(some) {
  document.write(some);
}
async function loadController(){
    let myPromise = new Promise(function(myResolve, myReject) {
      let req = new XMLHttpRequest();
      req.open('GET', "controllerDummy.html");
      req.onload = function() {
        if (req.status == 200) {
          myResolve(req.response);
        } else {
          myReject("File not Found");
        }
      };
      req.send();
    });
    
    myPromise.then((result)=>{
      myDisplayer(result);
    }).catch((error)=>{
      //handle error
    });
    
}

loadController()


推荐阅读