Question about asynchronous fetch

I’m new to asynchronous Javascript and can’t figure out how to return a fetched html page as a string. All that is being returned is a promise, which I have tried to access with .then(), but have had no luck. Here is what I’m working with:

async function getHtml() {
    const response = await fetch('url'); 
    const responseHTML = await response.text();
    return responseHTML;
}

Your getHtml() function looks fine to me (assuming you are replacing 'url' with an actual url). You are correct, it will return a Promise because all functions declared with async return a Promise. So you need to handle that correctly. Can you give us an example of how you are using this function in your code?

2 Likes

I’d like to take to take the returned string and filter it with regex. So if it was a normal function I’d write something like this:

async function getHtml() {
    const response = await fetch('url'); 
    const responseHTML = await response.text();
    return responseHTML;
}
const returnedString = getHtml();
const re = new RegExp('([A-Z])\w+', 's');
const filteredString = returnedString.match(re);

But that obviously doesn’t work with promises.

Right, you can’t just call getHtml() as a regular function since it returns a promise. You have a few options:

  • getHtml().then(html => {...});
  • create another async function and call getHtml() inside of it using await:
async processHtml() {
  const html = await getHtml();
  ...
}

Also, remember that it is possible that the fetch can fail so you probably want to add in error handling as well.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.