API请求获取PromiseResult数组对象后无法读取属性的问题
问题:Fetch请求后无法读取返回数组的属性
我用fetch发起API请求后,尝试读取返回数组中的值时遇到问题。明明能在PromiseResult中看到所有对象已成功获取,但用object[0].propertyName读取属性时提示无法读取。以下是我的完整方法及尝试过的操作:
methods: { fetchByteArray() { this.post = true; this.loading = false; //Docs\\003 console.log("inside FetchByteArray"); fetch('https://localhost:5001/api/Doc/GetFolder/003') .then(response => { console.log(response.json()); //console.log(JSON.stringify(response)); //console.log(response.body); let result = Promise.resolve(response); result.then(val => console.log(val)); }) .then(bytes => { //console.log(bytes); //this.byteArrays = bytes; console.log(bytes.fileName); }) .catch(error => console.log(error.message)); } }
控制台显示的PromiseResult结构如下:
[[PromiseResult]] : Array(6) 0 : {fileID: 0, fileName: 'image00.png', fileExtension: '.png', filePath: 'C:\\Users\\user1\\Documents\\zTests\\Docs\\003', byteArray: 'System.IO.MemoryStream', …} 1 : {fileID: 1, fileName: 'image01.png', fileExtension: '.png', filePath: 'C:\\Users\\user2\\Documents\\zTests\\Docs\\003', byteArray: 'System.IO.MemoryStream', …}
问题原因及修复方案
你的代码有两个核心问题:
- 未正确解析JSON响应:
response.json()返回的是Promise对象,直接打印它只能看到Promise状态,没有完成解析并传递数据。 - then链数据传递断裂:第一个then回调没有返回任何值,导致第二个then中的
bytes为undefined,自然无法读取属性。
修复后的代码:
methods: { fetchByteArray() { this.post = true; this.loading = false; console.log("inside FetchByteArray"); fetch('https://localhost:5001/api/Doc/GetFolder/003') .then(response => response.json()) // 解析JSON并返回Promise,传递到下一个then .then(bytes => { // bytes现在是解析完成的数组 console.log(bytes[0].fileName); // 访问数组第一个元素的fileName属性 this.byteArrays = bytes; }) .catch(error => console.log(error.message)); } }
补充说明
response.json()会将响应体解析为JSON格式,它本身是Promise,必须通过then回调获取解析后的数据。- then链中每个回调需要返回要传递的数据或Promise,才能让后续then拿到正确的结果。
- 接口返回的是数组,因此要访问元素必须使用数组下标(如
bytes[0]),直接用bytes.fileName无效,因为数组本身没有该属性。
内容的提问来源于stack exchange,提问作者Bigbear
相关产品推荐
相关产品推荐

