0

I have these lines here

let users = []
members.forEach(member => {
  let profile

  db.get(member.id).then(value => {
    profile = JSON.parse(value)
  })

  if(profile == null)
    return

  if(profile.bank + profile.cash > 0)
  {
    let user = new User(member, profile)
    users.push(user)
  }
})
console.log(users)

I want to save User objects into the users array, but outside the forEach loop, it is undefined. Can anyone help me?

Dave
  • 69
  • 6
  • 3
    Because it is ASYNCHRONOUS. The code after the callback does not magically sit there and wait for it to be called. – epascarello Jun 17 '22 at 18:32
  • `db.get(member.id).then(value => { console.log("callback", member.id); profile = JSON.parse(value) }); console.log("after", member.id);` – epascarello Jun 17 '22 at 18:34
  • Here's a [visualizer](http://latentflip.com/loupe/) represent what @epascarello mentioned – Dilshan Jun 17 '22 at 18:38
  • Does this answer your question? [Best way to wait for .forEach() to complete](https://stackoverflow.com/questions/38406920/best-way-to-wait-for-foreach-to-complete) – Hogan Jun 17 '22 at 18:39
  • I've tried the solution from Douglas Rosebank but it still doesn't work. @Hogan – Dave Jun 17 '22 at 19:00
  • @Dave -- interesting .. what exactly did you try and what exactly did it do? – Hogan Jun 17 '22 at 19:02
  • What is `db.get`? What library? – epascarello Jun 17 '22 at 19:19

1 Answers1

2

You problem is how javascript works --

 (member => 

represents a function call. But that function may not be finished by the time you get to your console log. You need a promise to make sure it is done.

Best way to wait for .forEach() to complete

Hogan
  • 69,564
  • 10
  • 76
  • 117