JS中fetch封装函数return返回undefined但console.log正常如何解决
问题原因
fetchData函数无显式返回值:你在函数内部仅将fetch的异步调用链赋值给了request变量,没有将该值返回,JavaScript中无return语句的函数默认返回undefined,这是你直接打印res得到undefined的核心原因。- fetch是异步API:它的返回值为Promise对象,即使你正确返回了异步调用链,也无法同步拿到接口返回的最终结果,必须通过Promise的
then回调或者async/await语法获取异步resolve的值。 - 额外细节:你现有过滤逻辑中未处理未传入
name参数的场景,此时第二个then回调无返回值,会导致异步结果为undefined。
修复方案
方案1:基于Promise then的写法
首先补全fetchData的返回逻辑:
const fetchData = ({ name, num }) => { // 新增return,将fetch返回的Promise暴露给外部调用方 return fetch(`apiLink`) .then((res) => res.json()) .then(data => { if (name) { return data.filter(person => person.name.includes(name)); } // 补充无name参数时的返回逻辑 return data; }) .catch(() => { console.error('oh no'); // 错误场景按需返回默认值,也可以抛出错误由上层处理 return []; }) }
调用时通过then获取最终结果:
fetchData({ name: 'Tina' }).then(res => { console.log(res); // 可正常输出过滤后的数组 })
方案2:基于async/await的写法(更易读,推荐)
const fetchData = async ({ name, num }) => { try { const res = await fetch(`apiLink`); const data = await res.json(); if (name) { return data.filter(person => person.name.includes(name)); } return data; } catch (err) { console.error('oh no', err); return []; } } // 调用示例:在async函数内用await接收结果 const getFilteredData = async () => { const res = await fetchData({ name: 'Tina' }); console.log(res); } getFilteredData();
内容的提问来源于stack exchange,提问作者wolfie777
相关产品推荐
相关产品推荐

