从SWAPI链接获取星战角色数据失败,代码为何仅返回链接数组?
问题原因及修正方案
你的代码存在三个核心问题,导致循环未执行:
未正确获取角色链接数组
fetch返回的是Promise对象,你直接将其赋值给people,但后续的.then回调里只打印了films.characters,却没有返回这个数组。因此people本质是一个已完成状态的Promise,而非数组,people.length为undefined,循环条件i < undefined不成立,循环根本不会运行。变量名错误
循环里写的是film.characters[i],但前面.then的参数是films,而且你根本没把角色链接数组存储到可访问的变量中。异步代码风格混乱
在async函数里混合使用.then和await,导致逻辑分层不清晰,更容易出现变量作用域和异步时序问题。
修正后的代码(逐个请求版本)
async function GetCharacters() { // 用await统一处理异步请求,获取影片数据 const filmResponse = await fetch("https://swapi.dev/api/films/2/"); const filmData = await filmResponse.json(); // 提取角色链接数组 const characterUrls = filmData.characters; // 遍历每个角色链接获取详情 for (const url of characterUrls) { const characterResponse = await fetch(url); const character = await characterResponse.json(); console.log(`角色名: ${character.name}`); console.log(`性别: ${character.gender}`); console.log(`出生年份: ${character.birth_year}`); console.log('---'); } } GetCharacters();
进阶优化:并行请求提高效率
如果想加快请求速度,可以用Promise.all并行发起所有角色请求,不用逐个等待:
async function GetCharacters() { const filmResponse = await fetch("https://swapi.dev/api/films/2/"); const filmData = await filmResponse.json(); // 将每个角色链接转为获取并解析数据的Promise const characterTasks = filmData.characters.map(async url => { const res = await fetch(url); const char = await res.json(); // 只保留需要的字段 return { name: char.name, gender: char.gender, birth_year: char.birth_year }; }); // 等待所有请求完成,拿到所有角色数据 const allCharacters = await Promise.all(characterTasks); console.log('所有角色信息:', allCharacters); } GetCharacters();
内容的提问来源于stack exchange,提问作者leopolis
相关产品推荐
相关产品推荐

