如何获取Axios请求返回Promise中[[PromiseResult]]的数组值?
解决方案
axios.get() 本身返回的是Promise异步实例,你直接赋值给RoomItems拿到的只是Promise对象本身,无法同步读取到内部的[[PromiseResult]]值,所有需要使用返回数组的逻辑,必须在异步上下文中执行。
方法1:使用.then()链式回调处理
所有依赖该数组的逻辑都写在.then()的回调函数内:
axios.get("./data.json") .then((res) => { const RoomItems = res.data // 此处即可正常访问数组、调用map方法 console.log(RoomItems) RoomItems.map(item => { // 编写你的业务逻辑 }) }) .catch(() => { console.log('fail') })
方法2:使用async/await语法(更推荐,写法更简洁)
await 必须包裹在被async修饰的函数中使用,语法接近同步写法,可读性更高:
// 声明异步请求函数 async function fetchRoomData() { try { const res = await axios.get("./data.json") const RoomItems = res.data // 此处可直接操作数组 console.log(RoomItems) RoomItems.map(item => { // 编写你的业务逻辑 }) return RoomItems } catch (err) { console.log('fail') } } // 调用函数执行请求 fetchRoomData()
注意不要尝试在异步逻辑外同步读取该数组的值,如果你是在Vue/React等前端框架中使用该数据,可将请求拿到的数组赋值给对应的响应式状态,再进行后续渲染或遍历操作。
内容的提问来源于stack exchange,提问作者Saebom Lee
相关产品推荐
相关产品推荐

