Per javascript.info, await
"suspends the function execution until the promise settles, and then resumes it with the promise result." If this is the case, why do we sometimes need multiple await
keywords within one function?
Consider the following example:
async function fetchdata() {
const response = await fetch("https://jsonplaceholder.typicode.com/users/")
const data = await response.json()
console.log(data)
}
fetchdata()
This returns an array of objects retrieved from the given URL. But if await
really suspends execution of fetchdata
, I would expect to get the same return value if I removed the second await
keyword, since the resulting const data = response.json()
should still only run once response
is settled.
However, when I run the below code, fetchdata()
returns a pending Promise, i.e. it appears response.json()
was run before response
was actually settled.
async function fetchdata() {
const response = await fetch("https://jsonplaceholder.typicode.com/users/")
const data = response.json()
console.log(data)
}
fetchdata()
Can someone explain to me what I am misunderstanding about the await
keyword?
CodePudding user response:
You need multiple await
statements because you have multiple promises.
The json()
method returns a promise (which resolves when the entire request body has been read and parsed).
This is because the promise returned by fetch()
resolves when the header list is available. This lets you make decisions about what to do next without waiting for the entire body to be transferred across the network.
It also lets you process the body as a stream using the body
property so you can handle a very large response piece by piece by piece as it comes in instead of storing the whole, raw response in memory.
CodePudding user response:
The json()
function itself needs awaiting because it returns a Promise