I started with JS and actually like the asynchronous aspects (coming from Python) but I am not sure why some functions return a Promise. Specifically, the following code using fetch
makes me wonder about what is returned by json()
:
fetch('https://freegeoip.net/json/8.8.8.8')
.then((response) => {
return response.json()
})
.then((json) => {
Object.keys(json).forEach((key) => {
console.log("got " + key)
})
})
Streaming aside, the HTTP response we get after a GET
is a block of text, which is later interpreted by the client to extract the headers, body and other interesting elements - as part of the analysis of the HTTP content.
The point is that this block of text comes in one piece, so the first then()
already has the whole response - why is the parsing of the JSON body an asynchronous operation, different from the forEach
in the second then()
?
In other words, why couldn't I have the followng code working?
fetch('https://freegeoip.net/json/8.8.8.8')
.then((response) => {
Object.keys(response.json()).forEach((key) => {
console.log("got " + key)
})
})
Note: please try to disable your adblocker if the first code does not run correctly (with a ERR_BLOCKED_BY_CLIENT
). The second one is intentionnaly incorrect.