为什么 .json() 是异步的?
- 论坛
- 为什么 .json() 是异步的?
9 浏览
为什么 .json() 是异步的?
我一直在跟随一个教程,遇到了以下代码片段:
const myAsyncFunction = async () => { const usersResponse = await fetch( 'https://jsonplaceholder.typicode.com/users' ) const userJson = await usersResponse.json(); const secondUser = userJson[1]; console.log(secondUser); const posts = await fetch ( 'https://jsonplaceholder.typicode.com/posts?userId=' + secondUser.id ); const postsJson = await posts.json(); console.log(postsJson); } myAsyncFunction();
将响应转换为JSON对象不应该立即发生,就像从数组中获取值(例如userJson[1]
)一样吗?为什么需要await
usersResponse.json()
和posts.json()
?