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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
"use strict"; // Fetch a random joke async function fetchQuote() { const rsp = await fetch( "https://www.7timer.info/bin/astro.php?lon=113.2&lat=23.1&ac=0&unit=metric&output=json&tzshift=0"); const data = await rsp.json(); return data.product; } async function sayJoke() { try { let result = await fetchQuote(); document.writeln( `Joke: ${ result }` ); } catch( err ) { console.error( err ); } } console.log('-- begin --'); sayJoke(); |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
async function fetchQuote() { return await fetch( "https://www.7timer.info/bin/astro.php?lon=113.2&lat=23.1&ac=0&unit=metric&output=json&tzshift=0").then( async (promise) => { const data = await promise.json(); // console.log(data) // the whole JSON object return data.product; // return a property of the data }) } async function sayJoke() { try { let result = await fetchQuote(); document.writeln( `Joke: ${ result }` ); } catch( err ) { console.error( err ); } } console.log('-- begin test --'); sayJoke(); |