如何在Promise执行完毕后保存结果,访问fetch请求返回的data数据
问题原因
你遇到的问题由两个核心错误导致:
- 异步执行顺序问题:
fetch是异步网络请求,你写在最外层的if判断代码会在请求返回结果之前就提前执行,此时data变量还未创建,自然无法访问到返回值。 - Promise链式返回值缺失:你第二个
.then()回调中只打印了data,没有将datareturn出去,所以后续调用resultPromise.then()时,回调拿到的参数会是undefined,无法获取到接口返回的数据。 - 额外拼写错误:你原有判断逻辑里的
ture是拼写错误,需要修正为true,否则判断逻辑也会执行异常。
解决方案
方案1:直接把业务逻辑写在then回调中(你更新2提到的方案,也是最常用的写法)
fetch(cleanUrl, { method: 'POST', // 也可以替换为'PUT' headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(body), }) .then(response => response.json()) .then(data => { console.log('Success:', data); // 业务逻辑直接放在此处,此时能拿到完整的返回数据 if(data.isSafe == true) { // 执行对应操作 } else { // 执行其他操作 } }) .catch((error) => { console.error('Error:', error); });
方案2:需要复用resultPromise时,补充return语句
如果你需要在其他地方也用到这个请求的返回结果,记得在.then()中返回data:
let resultPromise = fetch(cleanUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(body), }) .then(response => response.json()) .then(data => { console.log('Success:', data); // 必须return data,后续的then回调才能拿到返回值 return data; }) .catch((error) => { console.error('Error:', error); }); // 后续使用数据时,必须写在then的回调中,不能放在最外层同步执行 resultPromise.then(data => { // 可选链判断避免请求失败后data为undefined时报错 if(data?.isSafe == true) { // 执行对应操作 } else { // 执行其他操作 } })
方案3:用async/await语法简化异步逻辑(写法更直观,和同步代码逻辑一致)
// 用立即执行async函数包裹,也可以放在其他async函数中执行 (async function() { try { const response = await fetch(cleanUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(body), }); const data = await response.json(); console.log('Success:', data); if(data.isSafe == true) { // 执行对应操作 } else { // 执行其他操作 } } catch (error) { console.error('Error:', error); } })()
内容的提问来源于stack exchange,提问作者Daolin
相关产品推荐
相关产品推荐

