2017-05-18 1 views
0

J'essaie des modules ES2015 dans la version 60.0.3102.0 de Chrome Canary. Mon fichier script.js se lit comme ceci:en utilisant chercher avec des modules ES2015 dans les Canaries

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

et mon fichier fetchJSON.js se lit comme ceci:

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

Je reçois l'erreur:

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

Répondre

3

Votre fonction fetchJSON ne retourne rien. À cause de cela, lorsque vous essayez d'enchaîner un .then sur le résultat de fetchJSON, vous obtenez le TypeError Uncaught - undefined.

Solution: retourner votre chaîne Promise dans votre fonction fetchJSON:

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

Je ne ai pas besoin: '.alors (data => {données de retour;});' – interwebjill