2017-05-18 38 views
0

我在Chrome Canary版本60.0.3102.0中嘗試了ES2015模塊。我的script.js文件讀取這樣的:在加納利用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功能沒有返回任何東西。因此,當你嘗試鏈接一個.fhen結果的fetchJSON時,你會得到Uncaught TypeError - 未定義。

解決方法:在你的fetchJSON函數返回自己的諾言鏈:

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

所以我其實並不需要: '。然後(數據=> {返回的數據;});' – interwebjill

相關問題