2016-11-16 15 views
2

ECMAScriptを新規に使用しているため、非同期でファイルをロードしようとしていますが、アクセスできません。promise()を使用した非同期ロードファイルの後のアクセスクラスECMAScript 6

main.jsは、基本的なクラスのエラーUncaught ReferenceError: test is not definedを取得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> 

出力内のクラスにアクセスしようとしている

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); 
    } 
} 

を持っています。

誰でも私を助けてください。

+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

ありがとう..これは私のために働く。 –

関連する問題