2

I have a firebase function that goes as follows:

exports.myFunction = functions.database.ref('/users/{id}/').onWrite((snapshot, context) => {

//do some processing here

var number;
snapshot.after.ref.parent.once('value').then((newSnapshot) => {
    number = newSnapshot.child('number').val();
});
console.log(number);

//do some processing with the use of var number

//returning the updates after processing
return snapshot.after.ref.update(updates);
});

I realized that the variable number is coming out to be undefined as the function that I am using to obtain the value of number is running asynchronously. However, I am unable to think of a method to convert this implementation so that it works the way I want it. Any help would be appreciated.

1 Answer 1

2

You can chain a new .then() to perform the processing on this number. For example:

exports.myFunction = functions.database.ref('/users/{id}/').onWrite((snapshot, context) => {

...
var number;
return snapshot.after.ref.parent.once('value').then((newSnapshot) => {
        number = newSnapshot.child('number').val();
    }).then((number) => {
        console.log(number);
        //do some processing with the use of var number
        snapshot.after.ref.update(updates);
    });
});
Sign up to request clarification or add additional context in comments.

3 Comments

It should work just like this, or am I wrong ? : snapshot.after.ref.parent.once('value').then(newSnapshot => { number = newSnapshot.child('number').val(); console.log(number); //do some processing with the use of var number });
How do I handle the last return statement in these cases? The updates that are returned are dependent on the processing done with var number.
You can return the whole chain. See my updated answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.