Node js undefined in foreach?

142 Views Asked by At

Hello I am using the node-craigslist package to scrape listings off of craigslist. I am having trouble processing my results.

client
  .search(options, '')
  .then((listings) => {
    listings.forEach((listing) => 
    console.log(listing.title),
    searchResults.title[counter] = listing.title

    );//end of listings foreach
  })//end of then listings

My issue is that only the first line of code in the listings.forEach actually work. So in this case, if I comment out the searchResults.title, it will print out the listing title. If I comment out the console.log and leave just the searchResults.title, that one will work. But they will never both work at once.

I must be getting the syntax wrong on this trying to do more than one thing in the for each.

1

There are 1 best solutions below

1
kat1330 On BEST ANSWER

In your case you should do the following:

client
  .search(options, '')
  .then((listings) => {
    listings.forEach((listing) => {
      console.log(listing.title);
      searchResults.title[counter] = listing.title;
    });//end of listings foreach
  })//end of then listings

You forgot curly brackets in your lambda expression.

Please read move about arrow functions here.