skip to Main Content

I have been given the task of reading a file, processing the data and returning the results. As it is an async process, I run into the problem where you cannot return from a .then, and an unresolved Promise is unresolved. I am using fetch. I know this issue has been discussed a lot, apologies. Here is code. Thank you.

function myFunction () {
    async function fetchData() {      
      await fetch("./my_file.txt")
        .then((res) => res.text())
        .then((text) => {
          //I want to return text here
        })
      .catch((e) => console.error(e));
    }
    const response = fetchData();
    //I can process the data here and then return it
    //process data
    //return results
}

2

Answers


  1. Try something like this:

    async function myFunction () {
        async function fetchData() {
          try {
            let f = await fetch("./my_file.txt");
            let text = await f.text();
            return text;
          }
          catch (ex) {
            console.error(ex);
          }
        }
    
        const response = await fetchData();
        //I can process the data here and then return it
        //process data
        //return results
    }
    
    Login or Signup to reply.
  2. You cannot immediately return the results, that is just impossible. You can always only return a promise for them, no matter how you write it.

    The easiest is to just return the chained promise:

    function myFunction () {
      return fetch("./my_file.txt")
        .then(res => res.text())
        .then(text => {
          // I can process the data here and then return it
          // process data
          // return results
        });
    }
    

    You can also use async/await instead of .then():

    async function myFunction() {
      const res = await fetch("./my_file.txt");
      const text = await res.text();
      // I can process the data here and then return it
      // process data
      // return results
    }
    

    Notice I’ve removed the .catch(e => console.error(e)) part from both. That should be done only by the caller of myFunction(). Or if you don’t return a result anywhere, e.g.

    function myFunction () {
      fetch("./my_file.txt") /*
    ^^ no return */
        .then(res => res.text())
        .then(text => {
          // I can process the data here
          // process data
          // output results
          // no return
        })
        .catch(e => {
          // output error
          console.error(e);
        });
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search