2017-05-18 3 views
0

私はChrome Canary Version 60.0.3102.0でES2015モジュールを試しています。マイscript.jsファイルは次のように読み取りますCanaryのES2015モジュールでフェッチを使用する

import {fetchJSON} from './functions/fetchJSON.js'; 

const configFile = 'config.json'; 

const init =() => { 
    fetchJSON(configFile) 
    .then((data) => {  // code fails here at ln.7 
     console.log(data); 
    }) 
    .catch(error => console.log(error)); 
}; 

init(); 

と私のfetchJSON.jsファイルは次のように読み取ります

export function fetchJSON(url) { 
    const fetchJSON = fetch(url) 
    .then(response => response.json()) 
    .then(data => { 
     console.log(data);  // data exists and is reported in the console 
     return data; 
    }); 
} 

私はエラーを取得しています:

script.js:7 Uncaught TypeError: Cannot read property 'then' of undefined 
    at init (script.js:7) 
    at script.js:14 

答えて

3

あなたfetchJSON機能何も返さないそのため、fetchJSONの結果を連鎖しようとするとUncaught TypeError - undefinedが発生します。

ソリューション:あなたのfetchJSON機能であなたの約束のチェーンを返す:

export function fetchJSON(url) { 
    return fetch(url) 
    .then(response => response.json()) 
    .then(data => { 
     return data; 
    }); 
} 
+0

だから私は実際には必要ありません。 '.thenを(データ=> {戻りデータ;});' – interwebjill

関連する問題