在 Canary 中使用带有 ES2015 模块的 fetch
using fetch with ES2015 modules in Canary
我正在 Chrome Canary 版本 60.0.3102.0 中试用 ES2015 模块。我的 script.js 文件内容如下:
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
您的 fetchJSON 函数没有 returning 任何东西。因此,当您尝试在 fetchJSON 的结果上链接 .then 时,您会收到 Uncaught TypeError - undefined。
解决方案:return fetchJSON 函数中的 Promise 链:
export function fetchJSON(url) {
return fetch(url)
.then(response => response.json())
.then(data => {
return data;
});
}
我正在 Chrome Canary 版本 60.0.3102.0 中试用 ES2015 模块。我的 script.js 文件内容如下:
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
您的 fetchJSON 函数没有 returning 任何东西。因此,当您尝试在 fetchJSON 的结果上链接 .then 时,您会收到 Uncaught TypeError - undefined。
解决方案:return fetchJSON 函数中的 Promise 链:
export function fetchJSON(url) {
return fetch(url)
.then(response => response.json())
.then(data => {
return data;
});
}