0

I'm trying to use template literals to pass input data to a function as below and I don't have a clue why it's not working. Tried everything already. It simple does not enter the cheerio $ function when I use ${}. If I write the exact word instead, it works.

module.exports = function scrap(keyword) {

  sources.forEach(async source => {
    axios.get(source.url).then(response => {
      const html = response.data;
      const $ = cheerio.load(html);
      console.log("the keyword is " + keyword);
      console.log("the source url is " + source.url)

      console.log(typeof keyword);
      console.log(`The keyword is "${keyword}"`);

      $(`a:contains("${keyword}")`, html).each(function() {
        console.log("entered")
        const title = $(this).text();
        const url = $(this).attr('href');

        articles.push({
          title,
          url,
          source: source.name,
        });
      });
    }).catch(err => {
      console.log(err);
    });
    console.log(articles)
  });

  return articles;
}

So let's say that if I try

 $(`a:contains("bananas")`, html).each(function () { ...

it will work.

Any hints why template literals are not working?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
vasquezfd
  • 1
  • 1
  • What's the error? – punund Jun 20 '22 at 22:43
  • I doubt that template literals are the problem here. This async code isn't wired up to the return value at all, so this function will always return an empty array, although it's unclear where `articles` was initialized. See [Using async/await with a forEach loop](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop) – ggorlen Jan 02 '23 at 06:34

0 Answers0