Race Status with Node.js and Firebase

I am new to Firebase and Node.js, but I am trying to do the following:

gameScoreRef.child(score["ss"][i][10]).once('value', function(snapshot) {
    if (!snapshot.val()) {
        // NULL
    } else {
        gameID = snapshot.val();
        console.log(gameID);
    }
});

var ref = gamesRef.child(gameID);
ref.update({
    aScore: parseInt(score["ss"][i][5]),
    hScore: parseInt(score["ss"][i][7])
});

So basically I make one Firebase call to get GameScore Ref, and once it is restored, it works fine, it will use this GameID to update the game score.

The error you selected is that gameIDit is null, and not because Firebase is null, the value displays correctly console.log(gameID)as 43, because it seems that the first Firebase call has not yet completed before the second Firebase call to update results?

How can i solve this?

+4
source share
1

gameScoreRef.child . gameScoreRef.child - , gameID , gamesRef.child(gameID).

 gameScoreRef.child(score["ss"][i][10]).once('value', function(snapshot) {
        if (!snapshot.val()) {
            // NULL
        } else {
            gameID = snapshot.val();
            console.log(gameID);
            var ref = gamesRef.child(gameID);
            ref.update({
               aScore: parseInt(score["ss"][i][5]),
               hScore: parseInt(score["ss"][i][7])
            });
        }



    });

    // "gameID" doesn't exist here!

retrieveScore, promise.

function retrieveScore(ref){

    return new Promise((resolve, reject) => {
        gameScoreRef.child(ref).once('value', snapshot => {
            if (!snapshot.val()) {
                return reject();

            resolve(snapshot.val());

        });
    });

}


retrieveScore(score["ss"][i][10]).then(gameID => {
    console.log(gameID);
    let ref = gamesRef.child(gameID);
    ref.update({
        aScore: parseInt(score["ss"][i][5]),
        hScore: parseInt(score["ss"][i][7])
    });

}).catch(err => {
   //Handle error
});

:

+1

Source: https://habr.com/ru/post/1675281/


All Articles