skip to Main Content

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


  1. 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
    enter image description here

    async/await is based on promise

    so, async/await has promise prototype (just take .text() …)
    and promise prototype is in pending state because it is not executed

    If you want to know about response.text(), you need to execute response.text() using await

    => console.log(await response.text())

    Login or Signup to reply.
  2. 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:

    useEffect(async () => {
          async function fetchConstitution() {
            let response = await fetch(constitution_text);
            console.log(response.text());
            return response
          } 
    
         await fetchConstitution()
        }, []);
    

    solution 2:

    useEffect(() => {
          function fetchConstitution() {
            return fetch(constitution_text)
            .then((response) => response)
          } 
    
          fetchConstitution()
          .then(() => return response)
        }, []);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search