1

How do I actually use await inside of a listener like this? I get await is a reserved keyword

getPosts = async () => {
        return firebase.database().ref('posts/').orderByChild('created').on('value', snapshot => {
            let newPosts = []
            snapshot.forEach(post => {
                let location = await geofire.get(post.key)
                console.log("nice location", location)
                newPosts.push(post)
            })
            this.setState({ allPosts: newPosts }, () => console.log(this.state.allPosts))
        })
    }
ARMATAV
  • 604
  • 6
  • 26
  • 1
    This arrow function `post => {}` should be `async` – Ele Nov 08 '18 at 23:13
  • @Ele yep - you got it... Every damn time dude :( – ARMATAV Nov 08 '18 at 23:15
  • All of your `forEach` iterations will resolve *after* `this.setState` runs. They're async, but you're not waiting for all of them to resolve before running `this.setState`. You could use `for...of` to keep the same scope and not invoke another function, or use `Promise.all()` to ensure all of your snapshots have resolved. – Charlie Schliesser Nov 08 '18 at 23:20
  • @CharlieSchliesser I could do the for...of but then you lose the scoping for the await keyword - where does that move to? You just get a `await is a reserved keyword` – ARMATAV Nov 08 '18 at 23:46
  • You don't lose any scoping. Your `.forEach` becomes `for (const post of snapshop) { let location = await ... }`. Does that make sense? – Charlie Schliesser Nov 09 '18 at 15:25
  • ah I see - thank you! – ARMATAV Nov 09 '18 at 21:19

0 Answers0