所以我正在學習 JavaScript Promises 并創建了一個網頁,顯示從目錄中另一個檔案派生的文本。它成功加載了站點和所有內容,但問題是即使在站點加載和訪問其他網頁的資料后,它仍然顯示加載圖示。我嘗試從檔案中洗掉承諾,當我再次訪問該網頁時,沒有加載圖示。所以我認為這個承諾有問題。
- 1.
controller.js
(主JS檔案)
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()
- 2.
controller.html
(主檔案)
<!DOCTYPE html>
<html style="background-color: black;">
<head>
<script type="text/javascript" src="controller.js"></script>
</head>
<body>
</body>
</html>
- 3.
controllerDummy.html
(承諾從中提取回應文本的虛擬檔案)
<!DOCTYPE html>
<html style="background-color: black;">
<body>Loading Controller</body>
</html>
這些是所有檔案,現在是螢屏截圖。
如您所見,promise 已加載,但站點仍在加載圖示。有什么解決辦法嗎?這是過時的方式還是什么?
uj5u.com熱心網友回復:
兌現承諾
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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/318803.html