遍历数组调用map后报错:data.data.children.map(...).then不是函数
解决
map(...).then is not a function的问题 嘿,我来帮你搞定这个报错!你遇到的问题核心很简单:数组的map()是同步方法,它返回的是一个新数组,根本不是Promise对象,所以没法链式调用.then()——这就是为什么会弹出那个错误提示。
另外我还注意到你代码里的一个小细节:Reddit返回的帖子数据都嵌套在hit.data里,直接写hit.score是拿不到值的,得改成hit.data.score才行哦!
情况1:只是同步提取数据(无异步操作)
如果你的需求只是把帖子的score、title、permalink整理成新数组,直接用map生成数组就行,完全不需要.then():
fetch('https://www.reddit.com/r/somesubreddit/hot/.json?count=20') .then(response => response.json()) .then(data => { // 用map生成整理后的数组 const output = data.data.children.map(hit => ({ score: hit.data.score, title: hit.data.title, permalink: hit.data.permalink })); // 这里可以对output做后续操作,比如打印、渲染到页面 console.log(output); }) .catch(err => console.error('请求出错啦:', err));
情况2:map里包含异步操作(比如每个帖子要额外请求数据)
如果你的map里有异步逻辑(比如每个帖子都要再发一次请求拿详情),那就要用Promise.all()来包装所有异步任务,再用.then()等待全部完成:
fetch('https://www.reddit.com/r/somesubreddit/hot/.json?count=20') .then(response => response.json()) .then(data => { // 把每个异步操作包装成Promise,放进数组 const asyncTasks = data.data.children.map(hit => { // 示例:请求帖子详情 return fetch(`https://www.reddit.com${hit.data.permalink}.json`) .then(res => res.json()) .then(detailData => ({ score: hit.data.score, title: hit.data.title, permalink: hit.data.permalink, // 新增异步获取的详情内容 content: detailData[0].data.children[0].data.selftext })); }); // 等待所有异步任务完成 return Promise.all(asyncTasks); }) .then(output => { // 这里的output就是所有异步操作完成后的完整数组 console.log(output); }) .catch(err => console.error('请求出错啦:', err));
内容的提问来源于stack exchange,提问作者Revolt
相关产品推荐
相关产品推荐

