JavaScript嵌套函数运行异常:仅第一个函数生效第二个无响应
问题根源
第二个函数完全无响应是三个明确的代码逻辑问题导致的:
- 你仅在
getCMSID内部声明了getCMSPage函数,从未主动调用它,JavaScript不会自动执行只定义不触发的函数 - 第一个接口拿到的
cmsPageId你只打印到了控制台,没有存入变量,getCMSPage里拼接URL用到的id是未定义的无效值,就算调用函数也会请求错误地址 - 两个接口有强依赖关系:第二个请求必须等第一个请求返回
cmsPageId之后才能发起,你当前的代码结构完全没处理这个先后顺序
修复方案
如果不需要刻意保留嵌套函数结构,直接按Promise链式调用的逻辑写最简洁:
const getCMSID = () => { const url = `${URL}/store-api/category`; const getIdReqConfig = { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'sw-access-key': `${API_KEY}`, }, }; fetch(url, getIdReqConfig) .then(res => res.json()) .then(json => { // 先存储第一个接口返回的目标ID const cmsPageId = json.elements[0].cmsPageId; console.log(cmsPageId); // 拿到ID后直接发起第二个请求 const cmsUrl = `${URL}/store-api/${cmsPageId}`; const getCmsReqConfig = { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'sw-access-key': `${API_KEY}`, }, }; return fetch(cmsUrl, getCmsReqConfig); }) .then(res => res.json()) .then(json => { console.log(json.sections); setLoading(false); }) .catch(err => console.error('请求异常:' + err)); }; // 记得在需要触发拉取逻辑的位置(比如页面挂载时)调用外层函数 getCMSID();
如果你确实要保留嵌套函数的写法,记住两个核心规则:内部函数要在拿到依赖数据后主动调用,函数依赖的动态值要通过参数传入,参考写法如下:
const getCMSID = () => { const url = `${URL}/store-api/category`; const getIdReqConfig = { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'sw-access-key': `${API_KEY}`, }, }; // 定义内部函数时声明接收id参数 const getCMSPage = (id) => { const cmsUrl = `${URL}/store-api/${id}`; const getCmsReqConfig = { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'sw-access-key': `${API_KEY}`, }, }; fetch(cmsUrl, getCmsReqConfig) .then(res => res.json()) .then(json => { console.log(json.sections); setLoading(false); }) .catch(err => console.error('请求异常:' + err)); }; fetch(url, getIdReqConfig) .then(res => res.json()) .then(json => { const cmsPageId = json.elements[0].cmsPageId; console.log(cmsPageId); // 拿到ID后主动调用内部函数,传入参数 getCMSPage(cmsPageId); }) .catch(err => console.error('请求异常:' + err)); };
内容的提问来源于stack exchange,提问作者user18628737
相关产品推荐
相关产品推荐

