Search code examples
javascriptasync-awaites6-promise

Fetch and async await always returninig undefined


one of my server calls took nearly 30 seconds to return the data so it's always getting undefined so I am using the async and promise to resolve this issue but getting "undefined". The following is my code piece Thanks in advance

   function fetchFunc() {
        fetch('https://jsonplaceholder.typicode.com/posts')
            .then(response => response.json())
            .then((json) => {
                // console.log(json)
                return json;
            })
    }

    function resolveAfter2Seconds() {
        return new Promise(resolve => {
                resolve(fetchFunc());
        });
    }

    async function asyncFunc() {
        debugger
        console.log("res" + resolveAfter2Seconds())
        let response = await resolveAfter2Seconds();
        console.log("response = " + response);
    }
    asyncFunc();

Solution

  • As peeps said earlier in comments when you expect a function to give you a value you should use return keyword for it. So, in this case, you actually returned the fetch response but forgot to return fetch promise value itself.

    So your code should look like this:

    function fetchFunc() {
      return fetch('https://jsonplaceholder.typicode.com/posts')
        .then(response => response.json())
        .then((json) => {
          // console.log(json)
          return json;
        })
    }
    
    function resolveAfter2Seconds() {
      return new Promise(resolve => {
        resolve(fetchFunc());
      });
    }
    
    async function asyncFunc() {
      debugger
      console.log("res" + resolveAfter2Seconds())
      let response = await resolveAfter2Seconds();
      console.log("response = " + response);
    }
    asyncFunc();