2016-11-16 75 views
2

异步加载文件后的访问类正在试图异步加载文件并访问类,但我不能这样做。使用promise()ECMAScript 6

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: test is not defined类。

任何人都可以请帮助我。

+0

见,所有的浏览器不支持ES6的所有功能。所以你必须使用像TypeScript或Babel这样的编译器。你可以在[Caniuse.com](http://caniuse.com/#search=class) –

回答

1

在致电new test()之前,您需要等待sttAsyncLoad完成。由于您使用的是承诺,因此您可以使用类似

sttAsyncLoad().then(function() { let sObj = new test("test", "test11"); }); 
+0

检查感谢您的回应。 –

1

您的脚本不会等到承诺解决。它会运行

let sObj = new test("test","test11"); 

不管脚本是否已经加载。

相反,使用承诺的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"); 
}); 
+0

谢谢你..这对我有用。 –

相关问题