I am trying to learn what seems to be a simple async call within a useEffect in React. My code is as follows:
useEffect(() => {
async function fetchConstitution() {
let response = await fetch(constitution_text);
console.log(response.text());
return response
}
fetchConstitution()
}, []);
It is my understanding that awaiting the fetch call means the code immediately after will not be run until the promise resolves from the fetch call. However, all I can seem to get is:
console output
The thing that is logged is a pending promise whose status is fulfilled. Doesn’t the await mean the promise will be handled similarly to doing the call and then using .then()? I have also tried refactoring the code using .then() and get the same result. How can I get the actual text (that can be seen from the PromiseResult) to be console logged?
2
Answers
JavaScript is Prototype Language
Prototype is object that provide shared properties for other objects in ECMA-262
So, JavaScript is linked as a prototype
like this
async/await
is based onpromise
so,
async/await
haspromise
prototype (just take .text() …)and
promise
prototype is in pending state because it is not executedIf you want to know about
response.text()
, you need to executeresponse.text()
usingawait
=>
console.log(await response.text())
If a function is defined as an Async function, that function will be executed asynchronously. Here the problem is, the fetchConstitution function is defined as an asynchronous function, So what javascript does is, Javascript doesn’t wait until that function is fully executed, it simply executes next line.
So here the solution is, When you call the async function you should use await, or you can use then catch.
Solution 1:
solution 2: