Axios and fetch both returns a Promise object

ref –

  • https://stackoverflow.com/questions/37555031/why-does-json-return-a-promise
  • https://stackoverflow.com/questions/67043652/why-is-response-json-returning-a-promise

Fetch will return a Promise object rsp.
However, when you access json() of rps, it also returns a promise.

Why is this?

Because you receive the response as soon as all headers have arrived.

Calling .json() gets you another promise for the body of the http response that is yet to be loaded.

So when the headers have arrived, the promise for the fetch will resolve. But in order to the data from the body, you’ll have to wait for the promise from json() to resolve.

Another way to do it is to receive the promise object from then callback.
It is a Promise, so we’ll have to wrap it with async.

This promise means the header has arrived. Then in order to receive the body data, we’ll have to do an await on the promise object’s json(), which returns another Promise.

Once this Promise resolves, it means the body data has arrived in data.