使用fetch()读取JSON文件并返回数组时无法传递结果的问题排查
问题分析与解决方案:异步函数返回值异常
这个问题其实是异步JavaScript里非常常见的坑——你遇到的是异步操作的执行顺序问题,我来给你拆解清楚:
核心原因:fetch是异步操作
fetch是一个异步网络请求API,它不会阻塞后续代码的执行。你的getOrderDays函数会先跑完所有同步代码(包括最后的return indexes),而then回调里的逻辑要等到网络请求完成、数据返回后才会执行。
更关键的是:你在then回调内部定义的indexes是局部变量,函数外层根本访问不到它。所以你最后return indexes的时候,要么是返回一个未定义的变量,要么是返回了一个你之前可能在全局作用域声明的空数组,自然得不到预期的结果。
解决方案:让函数返回Promise,通过异步方式获取结果
我们需要把异步操作的结果通过Promise传递出来,有两种常用写法:
写法1:直接返回fetch的Promise链
修改函数,让它返回整个fetch的Promise流程,在then里返回最终的indexes:
function getOrderDays(file, col){ const myRequest = new Request(file); // 返回整个Promise链 return fetch(myRequest) .then(response => response.json()) .then(data => { const selecteddata = []; data.forEach(item => { selecteddata.push(parseInt(item[col])); }) const indexes = [0]; let i = 0; while (data[i]) { if (selecteddata[i] !== 0) { indexes.push(i); } i++; } console.log(indexes); return indexes; // 在这里返回结果,会被传递到调用方的then中 }).catch(err => { console.error(err); throw err; // 抛出错误,让调用方可以捕获处理 }); } // 调用方式:通过then接收结果 getOrderDays('你的JSON文件路径', '目标列名') .then(indexes => { // 在这里使用indexes创建图表 console.log('用于创建图表的数组:', indexes); }) .catch(err => { // 处理请求或解析错误 });
写法2:用async/await简化异步代码
如果觉得Promise链的写法不够直观,可以用async/await语法,让代码看起来更像同步逻辑:
async function getOrderDays(file, col){ try { const myRequest = new Request(file); const response = await fetch(myRequest); const data = await response.json(); const selecteddata = []; data.forEach(item => { selecteddata.push(parseInt(item[col])); }) const indexes = [0]; let i = 0; while (data[i]) { if (selecteddata[i] !== 0) { indexes.push(i); } i++; } console.log(indexes); return indexes; } catch (err) { console.error(err); throw err; } } // 调用方式1:在async函数中使用await async function initChart() { try { const indexes = await getOrderDays('你的JSON文件路径', '目标列名'); // 在这里用indexes创建图表 } catch (err) { // 处理错误 } } initChart(); // 调用方式2:依然可以用then getOrderDays('你的JSON文件路径', '目标列名') .then(indexes => { // 使用indexes }) .catch(err => { // 处理错误 });
额外提示
- 尽量用
const/let替代var,避免变量提升带来的意外问题 - 判断不等于0的时候,用
!==严格不等于比!=更严谨 - 一定要处理
catch的错误,避免网络请求失败时程序崩溃
内容的提问来源于stack exchange,提问作者Nicola Ibba
相关产品推荐
相关产品推荐

