使用Axios调用Pokemon API获取列表时仅返回Promise问题排查
问题:调用async方法获取宝可梦列表得到Promise对象而非结果
你的代码调用pokemon.all()后直接打印得到Promise { <pending> },核心原因是async函数的返回值本身就是Promise对象,不管内部是否使用await,直接赋值变量拿到的都是未决议的Promise,而非最终结果。另外代码里还有个多余的await:response.data.results.map(...)是同步操作,不需要加await。
问题代码
import axios from "axios"; class Pokemon { async all() { try{ const response = await axios.get("https://pokeapi.co/api/v2/pokemon?limit=9") return await response.data.results.map(item => item.name) }catch (error){ console.log(error); } } } const pokemon = new Pokemon const listPokemon = pokemon.all(); console.log(listPokemon); // Promise { <pending> }
修复方案
方案1:用async/await处理调用(推荐)
需要在一个async函数里调用pokemon.all(),并用await获取结果:
import axios from "axios"; class Pokemon { async all() { try{ const response = await axios.get("https://pokeapi.co/api/v2/pokemon?limit=9") // map是同步操作,去掉多余的await return response.data.results.map(item => item.name) }catch (error){ console.log(error); } } } const pokemon = new Pokemon; // 用async立即执行函数处理 (async () => { const listPokemon = await pokemon.all(); console.log(listPokemon); // 输出宝可梦名称数组 })();
方案2:用.then()链式调用结果
如果不想用async函数,也可以通过Promise的then方法获取resolved后的结果:
import axios from "axios"; class Pokemon { async all() { try{ const response = await axios.get("https://pokeapi.co/api/v2/pokemon?limit=9") return response.data.results.map(item => item.name) }catch (error){ console.log(error); } } } const pokemon = new Pokemon; pokemon.all().then(listPokemon => { console.log(listPokemon); // 输出宝可梦名称数组 });
关键要点
- async函数必然返回Promise,必须通过
await(在async函数内)或.then()来获取最终结果 - 同步操作(比如数组map)不需要加await,否则是无效的多余代码
内容的提问来源于stack exchange,提问作者Stark
相关产品推荐
相关产品推荐

