2017-05-18 5 views
0

Ich versuche ES2015-Module in Chrome Canary Version 60.0.3102.0. Meine script.js Datei liest sich wie folgt:mit fetch mit ES2015-Module in Canary

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

und meine fetchJSON.js Datei liest sich wie folgt:

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

Ich erhalte die Fehlermeldung:

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

Antwort

3

Ihre fetchJSON Funktion gibt nichts zurück. Aus diesem Grund, wenn Sie versuchen, ein .then auf das Ergebnis von fetchJSON zu verketten, erhalten Sie den Uncaught TypeError - undefined.

Lösung: Bringen Sie Ihr Versprechen Kette in Ihrer fetchJSON Funktion:

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

ich also eigentlich nicht brauchen: '.then (data => {return Daten;});' – interwebjill