Fetch api,为什么我必须在响应 json() 上使用 then,试图使承诺有意义
Fetch api, why do I have to use then on the response json(), trying to make sens of promises
我试图理解 promises,所以我在 twitch 上尝试了一个简单的获取请求。我不明白的是为什么 json()
returns 是一个承诺。为什么 ?响应中已经包含了数据,那为什么还要承诺呢?
fetch('https://api.twitch.tv/kraken/games/top?limit=10&offset=0')
.then( resp => {
resp.json()
.then(function(data) {
console.log(data);
});
});
换句话说:第一个then
,我明白了,它等待响应。然而,当进入 then 函数时,这意味着已经收到响应,因此数据应该可以立即访问,而不需要另一个承诺。这让我很困惑。
来自docs:
The response of a fetch() request is a Stream object, which means that
when we call the json() method, a Promise is returned since the
reading of the stream will happen asynchronously.
我试图理解 promises,所以我在 twitch 上尝试了一个简单的获取请求。我不明白的是为什么 json()
returns 是一个承诺。为什么 ?响应中已经包含了数据,那为什么还要承诺呢?
fetch('https://api.twitch.tv/kraken/games/top?limit=10&offset=0')
.then( resp => {
resp.json()
.then(function(data) {
console.log(data);
});
});
换句话说:第一个then
,我明白了,它等待响应。然而,当进入 then 函数时,这意味着已经收到响应,因此数据应该可以立即访问,而不需要另一个承诺。这让我很困惑。
来自docs:
The response of a fetch() request is a Stream object, which means that when we call the json() method, a Promise is returned since the reading of the stream will happen asynchronously.