如何在fetch API的.then()中向Array.map()生成的数组返回对象?
解决Array.map中调用fetch异步填充数组的问题
你的核心问题是fetch是异步操作,而Array.map是同步遍历,所以直接在map里操作拿不到最终结果。原代码里map的回调函数没有返回fetch的Promise,导致accdata全是undefined;就算返回了Promise,也需要等待所有异步请求完成后才能处理结果。
解决方案步骤
- 让map返回每个fetch请求的Promise,得到一个Promise数组
- 用
Promise.all等待所有Promise完成,拿到所有请求的结果 - 过滤掉不符合条件(
data == null)的项,得到最终数组
修改后的代码(Promise链式写法)
// 第一步:生成包含所有fetch请求的Promise数组 const promiseArray = data.map((each) => { return fetch(`http://localhost:3001/messenger/checker/${each._id}`, { credentials: 'include' }) .then(res => res.json()) .then(fetchedData => { // 仅当接口返回数据不为null时保留each,否则返回null return fetchedData != null ? each : null; }) .catch(err => { console.log(err); // 捕获错误后返回null,避免单个请求失败导致整体Promise.all报错 return null; }); }); // 第二步:等待所有请求完成,过滤无效值 Promise.all(promiseArray) .then(results => { const accdata = results.filter(item => item !== null); // 这里可以使用accdata做后续业务操作 console.log(accdata); }) .catch(err => { console.log('批量请求出错:', err); });
更简洁的async/await写法
async function getValidAccData() { // 生成Promise数组 const promiseArray = data.map(async (each) => { try { const res = await fetch(`http://localhost:3001/messenger/checker/${each._id}`, { credentials: 'include' }); const fetchedData = await res.json(); return fetchedData != null ? each : null; } catch (err) { console.log(err); return null; } }); // 等待所有请求完成并过滤结果 const results = await Promise.all(promiseArray); return results.filter(item => item !== null); } // 调用并使用结果 getValidAccData().then(accdata => { console.log(accdata); // 后续操作 });
为什么临时数组方法无效?
因为fetch的回调函数是异步执行的,会在当前同步代码(比如map遍历)执行完后才进入事件队列。当你尝试用临时数组存储时,map已经遍历完成,但此时所有fetch的回调还没执行,临时数组还是空的,你无法准确判断所有请求何时完成。而Promise.all会统一等待所有异步操作结束,是处理批量异步请求的标准方式。
内容的提问来源于stack exchange,提问作者yabadaba
相关产品推荐
相关产品推荐

