0

I'm trying to run a foreach loop and add values to an array, but it's not working properly. The values in the first foreach get added properly, but none of the values in the second foreach loop get added.

My code is:

categories.forEach(async function (cat) {
        te.push({ params: { slug: [cat.cat_slug] } })
        var articles = await db.query(escape`
                SELECT *
                FROM articles
                WHERE category = ${cat.id}
            `)
        articles.forEach(function (art) {
            te.push({ params: { slug: [cat.cat_slug, art.slug] } })
        })

    })

Any ideas?

Esteban89
  • 671
  • 1
  • 8
  • 20
  • How do you determine they aren't added? Isn't this simply [async code](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron)? – VLAZ Jun 05 '20 at 23:42
  • I run console logs on all the instances and only the pushs in the first foreach are adding the content – Esteban89 Jun 05 '20 at 23:43
  • What package, library or framework are you using to query the db? What is `db` and instance of? – ggordon Jun 05 '20 at 23:45
  • I'm using serverless mysql, that part is working properly, if I console.log articles right after I declare the var I get all the right content – Esteban89 Jun 05 '20 at 23:46
  • If I console log [cat.cat_slug, art.slug] before the push I also get the right content – Esteban89 Jun 05 '20 at 23:47
  • You sure you want to be making SELECT statements in a loop, seems highly wasteful. I'd compose the select, and then make ONE select.. rather than "n" number of them. – james emanon Jun 06 '20 at 00:18

1 Answers1

1

According to this answer Using async/await with a forEach loop Async can't be used inside foreach loops, I had to use a for loop instead and it got fixed.

Esteban89
  • 671
  • 1
  • 8
  • 20
  • Yes, don’t use forEach with asynchronous code, forEach expects synchronous function, use for loop. – Lukas C Jun 28 '20 at 14:11