A fetch API request will only fail if there is a network or server error. So for example, if I execute the following code, assuming it went through the try
block without an error, I will have a valid populated res
.
try {
const res = await fetch('/createurl', {
method: 'POST',
body: 'testData',
headers: {
'Content-Type': 'application/json'
}
})
if (res.ok) {
alert('Resource created!')
} else {
alert('Error creating resource!')
}
flashResponseToUser(res)
} catch(e) {
alert('A server or network error occurred during the request!')
}
I am handling res
to show the users the necessary error
or success
message using the flashResponseToUser(res)
function. Since res.json()
returns a Promise
, flashResponseToUser
has to be an async function.
const flashResponseToUser = async(res) => {
const jsonRes = await res.json() // Get data from response
console.log(jsonRes)
}
I want to know:
- Why does
res.json()
return aPromise
since at this point the response has already been received by the client? - Under what conditions would the
Promise
returned byres.json()
fail? - Does the code within
flashResponseToUser(res)
also need to be wrapped within atry-catch
block since I am usingres.json()
?