如何读取Promise.all双fetch请求返回的JSON数据?
如何正确读取Promise.all多fetch请求的结果?
我使用Promise.all发起了如下的“双fetch”请求:
Promise.all([ fetch('https://jsonplaceholder.typicode.com/posts'), fetch('https://jsonplaceholder.typicode.com/users') ]).then(function (responses) { // Get a JSON object from each of the responses return Promise.all(responses.map(function (response) { return response.json(); })); }).then(function (data) { // Log the data to the console // You would do something with both sets of data here console.log(data); }).catch(function (error) { // if there's an error, log it console.log(error); });
我的问题是如何正确读取这些fetch请求的结果?这两个URL返回的数据结构不同,我知道data[0]对应posts数据、data[1]对应users数据,但在提取特定数据时遇到了极大困难。比如我尝试过以下写法:
console.log(data[1].address[0].street); console.log(data[1].address.street); console.log(data[0].title); console.log(data[0].title[3]);
问题根源:没理清返回数据的结构
首先明确两个接口返回的都是数组:
/posts返回帖子数组,每个元素是含title、body等属性的帖子对象/users返回用户数组,每个元素是含name、address等属性的用户对象,其中address是子对象,包含street、city等属性
你的写法错误在于:直接给数组本身访问对象属性(比如data[0].title),或者搞反了数组索引与对象属性的顺序(比如data[1].address[0].street)。
正确读取方式
1. 先通过数组索引定位元素,再访问对象属性
.then(function (data) { // 取第一个帖子的标题 console.log(data[0][0].title); // 取第四个帖子的标题(数组索引从0开始,[3]对应第4个元素) console.log(data[0][3].title); // 取第一个用户的街道地址 console.log(data[1][0].address.street); // 取第二个用户的城市 console.log(data[1][1].address.city); })
2. 用解构赋值让代码更直观
把data解构为posts和users,避免记data[0]、data[1],可读性更强:
.then(function ([posts, users]) { // posts 是帖子数组,users 是用户数组 console.log(posts[0].title); // 第一个帖子标题 console.log(users[0].address.street); // 第一个用户的街道 })
3. 遍历数组处理所有数据
如果要处理全部帖子或用户,用循环遍历:
.then(function ([posts, users]) { // 遍历所有帖子,打印标题 posts.forEach(post => { console.log(post.title); }); // 遍历所有用户,打印姓名和街道 users.forEach(user => { console.log(`${user.name} 的地址:${user.address.street}`); }); })
小技巧:先打印完整数据看结构
遇到数据结构不明确的情况,先在控制台打印data、posts或users,展开查看层级结构,再一步步定位到需要的属性,避免凭猜测写代码。
内容的提问来源于stack exchange,提问作者Pangit
相关产品推荐
相关产品推荐

