user5855304
user5855304

Reputation:

Callbacks/Promises in Firebase

I trying to figure out why i am getting objects in //1 and //2 but getting undefined at //3...

I am messing around Angular2 with Typescript and Firebase back end.

What am i doing wrong here, seems to me like a rookie mistake...

    getPlayers() {
        var snap;
        this.playersRef.once('value', function (snapshot) {
                snap = snapshot.val();
//1
                console.info("snap.val()" + snapshot.val());
//2
                console.info("var snap" + snap);

            }
        );
//3
        console.info("var snap loc 2" + snap);
        //return new Promise<Player[]>(resolve => resolve(snap));
    }

///////// EDIT /////////////////////////////////////////////

Can someone explain how this pertains to the Firebase nosql DB in particular (Inside of Angualr2 app).

in my app.component.ts file i have this

    constructor(private _playerService: PlayerService){}

    getPlayers(){
        this._playerService.getPlayers().then(res => this.players = res);
    }

    ngOnInit(){
        this.getPlayers();
    }

inside the player.service.ts file I have this

getPlayers() {
    this.playersRef.once('value', function (snap){
        return snap.val();
    });
}

I always get TypeError: this._playerService.getPlayers(...) is undefined

I've read some atricle such as this https://www.firebase.com/blog/2016-01-21-keeping-our-promises.html

but i still can't figure out how to make everything work together.

Also when i try to edit my getPlayer() with promises (insead of callbacks) like in the article i get an exception stating that .once() needs at least two parameters so I'm not sure how the article is working at all with .once('value').then()

Upvotes: 0

Views: 353

Answers (2)

Carcigenicate
Carcigenicate

Reputation: 45826

It's undefined since //3 is executed immediately, even though the callback may not necessarily have run by the time the //3 log statement is called, meaning snap won't have been set yet. It's not undefined because of scoping issues, it's undefined because it's not set at the time you check the value.

Running this, you should realize that //3 immediately gives you undefined, then //1 prints, then //2 prints. Think about that.

Upvotes: 1

Jonathan.Brink
Jonathan.Brink

Reputation: 25443

It looks like this.playersRef.once is asynchronous.

This means that the third console statement will run prior to the callback of once executing, thus the snap variable will still be undefined at that point in time.

So, the sequence of console statements is actually 3, 1, 2, rather than 1, 2, 3.

Upvotes: 1

Related Questions