Renaud Tarnec
Renaud Tarnec

Reputation: 83048

Passing a value between chained Promises in Cloud Functions for Firebase

I am implementing a Stripe payment module in a Firebase web application.

I create a Stripe charge through a Cloud Function, as follow:

exports.createStripeCharge = functions.database.ref('...').onWrite(event => {
....
    let chargeStatus;

return stripe.charges.create(charge, {idempotency_key})
    .then(returnedcharge => {
        chargeStatus = returnedcharge.status;
        return event.data.adminRef.set(returnedcharge)
    })
    .then(() => {
        return admin.database().ref(`/stripeCardCharges/${event.params.orderId}`).set({'status': chargeStatus});
    })
    .catch(error => {
        ...
    })

As you see I try to follow the advices from the Firebase team to carefully chain the promises.

However I need the returnedcharge object to be used in two promises, chained one after the other:

  1. The first time to write the entire object to the Real Time Database
  2. The second time because I want to write returnedcharge.status to the database, but at another node (because of different access rights)

I have then created a variable that I populate in the first promise and use later in the next one.

My question is: Is this the good approach?

Another linked question (for which I think the answer is "no"!): would it be possible (and make sense!) to combine the two database write (i.e. set) in one promise only? If yes, what do you return then?

Upvotes: 3

Views: 988

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317352

Looks OK to me. Seems to get the job done without problems.

Upvotes: 1

Related Questions