'How to get replace url in a text string promises

I have a function where I get urls from a string, then I run another function to fetch url data(metadata). Now I want to replace the url, with some data from the metadata function.

Unfortunately, I can't get this to work the way I want.

Here is the async function:

export async function scrapeContentForLink(status): Promise<any>  {

   const statusRef = URI.withinString(status.status, ( async (url) => {
       const data =  await getUrlMetaData(url);
       return data;

  }))

  console.log(statusRef);

  return statusRef;
}

And here is the getUrlMetaData(url) method:

getUrlMetaData(url){
  ....
  return metadata;
}

When i try it out with a string as this:

https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery The slide-toggle behaves similarly to a checkbox, though it does not support an indeterminate state like .

Note: the sliding behavior for this component requires that HammerJS is loaded on the page. https://material.angular.io/components/slide-toggle/overview

It gives me the below result. Instead of replacing the urls, with the data variable.

[object Promise] The slide-toggle behaves similarly to a checkbox, though it does not support an indeterminate state like .

Note: the sliding behavior for this component requires that HammerJS is loaded on the page. [object Promise]

What would be the way to handle this properly?



Solution 1:[1]

URI.withinString is not async, and expects any supplied callback function to complete synchronously.

You might consider collecting the urls first, performing your metadata lookup asynchronously, and then running withinString a second time to do the desired replacement.

e.g.,

async function getUrlMetadata(url: string) {
    // ...
    return `[Metadata for ${url}]`;
}

export async function scrapeContentForLink(status): Promise<any> {
    const urls = [];
    URI.withinString(status.status, url => urls.push(url));

    const data = [];
    for (const url of urls) {
        data.push(await getUrlMetadata(url));
    }

    return URI.withinString(status.status, () => data.shift());
}

This will replace each detected URI with the result of the getUrlMetadata function:

    const result = await scrapeContentForLink({
        status: 'This text has links to https://www.example.com/this.txt and also https://www.example.com/that.txt.',
    });

    // "This text has links to [Metadata for https://www.example.com/this.txt] and
    // also [Metadata for https://www.example.com/that.txt].""
    console.log(result);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Myk Willis