我是 ECMAScript 新手,正在尝试异步加载文件并访问该类,但无法这样做。
我的main.js
有基本类
console.log("=============in main script=================")
class test{
constructor(auth_key,auth_secret){
this.auth_key = auth_key;
this.auth_secret = auth_secret;
console.log("============In class test============");
}
init(){
console.log("============In init function============"+this.auth_key);
}
}
尝试访问index.html
中的类
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<script type="text/javascript">
function sttAsyncLoad(){
console.log("===========loading script asynchronously============");
return new Promise(function (resolve, reject) {
var s;
s = document.createElement('script');
s.src = "src/main.js";
s.onload = resolve;
s.onerror = reject;
document.head.appendChild(s);
});
}
sttAsyncLoad();
let sObj = new test("test","test11");
</script>
</body>
</html>
输出出现错误Uncaught ReferenceError:测试未定义
。
谁能帮帮我。
最佳答案
您的脚本不会等到 promise 得到解决。它将运行
let sObj = new test("test","test11");
立即,无论脚本是否已加载。
相反,使用promise的then()
来等待它解析:
function sttAsyncLoad(){
console.log("===========loading script asynchronously============");
return new Promise(function (resolve, reject) {
var s;
s = document.createElement('script');
s.src = "src/main.js";
s.onload = resolve;
s.onerror = reject;
document.head.appendChild(s);
});
}
sttAsyncLoad().then(function() {
let sObj = new test("test","test11");
});
关于javascript - 使用 Promise() ECMAScript 6 异步加载文件后访问类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40634492/