cancel
Showing results for 
Search instead for 
Did you mean: 

Get value out of firestore promise function

Options
akheersoum090
Contributor
Posted on

I'm trying to integrate the Paypal Smart Button and Firestore. Everything was working fine until I tried to add in a check to see if the user document already existed in Firestore to throw an error so users can't register twice.

The next Paypal action (onApproval facial) requires the subscription id, which is created by the actions.subscription.create() function.

Just to make sure it wasn't a problem with the way the function fired, I also ommitted it, and just had paypalCreate = 'success'. But when logging the result of paypalCreate, at different levels of the nested functions, these were the results and their order:

On Fail (user exists):

  • Third Creation error
  • First Creation error
  • Second Creation error

On Success (user doesn't exist):

  • Third Creation success
  • First Creation success

So why is the 'Third Creation' always logged first? I'm guessing because the promise hasn't completed. Do I need to add a wait somewhere?

And on success, why isn't the 'Second Creation' returned? How is it any different to the failed result?

I need paypalCreate returned at the end of this createSubscription function, so the next step can use the result of it.

The code simplified:

createSubscription: function(data, actions) {

    // Get snapshot
    db.collection('users').doc(email).get().then((querySnapshot) => {
        let paypalCreate;

        // Check if email exists
        if (querySnapshot.exists) {
            // Register as error if user exists <- This works
            paypalCreate = 'error';
            console.log('First Creation ' + paypalCreate);

        } else {
            console.log("user doesn't exists");

            // Saving new user to Firestore <- This works
            db.collection('users').doc(email).set({
                name: name,
                email: email,
                created: firebase.firestore.Timestamp.now()
            }),

            // Choose plan to subscribe to in PayPal
            paypalCreate = actions.subscription.create({
                'plan_id': 'XXXX'
            });

            console.log('First Creation ' + paypalCreate);
            return paypalCreate;

            };
            console.log('Second Creation ' + paypalCreate);
            return paypalCreate;
        }),
        console.log('Third Creation ' + paypalCreate);
        return paypalCreate;
    },

 

Haven't Found your Answer?

It happens. Hit the "Login to Ask the community" button to create a question for the PayPal community.