1
let pages = {}
    let commandSections = await fs.readdirSync("./commands")
    
    let pageNum = 1
    await commandSections.forEach(async e => {
      let sectionCommands = await fs.readdirSync(`./commands/${e}`)
      let pageInfo = ''
      await sectionCommands.forEach(async element => {
        let desc = await client.commands.get(element.split(".")[0]).description
        pageInfo += `${element.split(".")[0]} - ${desc}\n`
      })
      pages[pageNum] = {"name": e, "value": pageInfo}
      pageNum++
    })

^^ my code is up there, and as you can see there, i define pages as a dictionary. i then proceed to have a few forEach loops (to loop through the commands of a discord bot), which add key/value pairs to the dictionary. the problem is, whenever i try to access the dictionary, it returns as an empty dictionary ({}). when i console.log "pages" inside the forEach loop though, it returns as the proper thing. any ideas?

Josh
  • 119
  • 1
  • 11
  • 1
    Short explanation : `forEach` and `await` doesn't go hand in hand, sure it would fire away the `async` calls but wouldn't wait for each of the promise resolution. Simply use normal for loop `for(let i = 0; i < length; ++i)` instead of `forEach` at both loops. should work. [More info](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop) – ambianBeing Sep 24 '20 at 18:10
  • [`async/await` with `forEach`](https://codeburst.io/javascript-async-await-with-foreach-b6ba62bbf404) – Lioness100 Sep 24 '20 at 18:24

1 Answers1

0

First of all You don't need to use await with fs.readdirSync becuse this method is not async.

You can't find docs for this method here

Potentially, the problem here is that forEach function doesn't wait for async callbacks.
It just calls callback You pass.
If you need to work with async operations within array iteration You better user for loop for that. It works perfectly with async code.