user7409576
user7409576

Reputation:

How to use promise in an argument function (Firebase transaction)?

Firebase transaction receives first argument as a function(any type). Can I use a method that returns promise inside this function? (in my case it's firebase-admin.auth().createUser()).

Some code for clarity:

const ref = admin.database().ref(...);
ref.transaction((currentData) => {
  if (currentData === null && ...) {
    admin
      .auth()
      .createUser({...})
      .then(data => return { uid: data.uid }) // Need to return this 'someData' from function that wraps current promise.
      .catch(() => return null)
  } else {
    return null
  }
});

In this code the function runs without waiting for promises to be resolved.

NodeJS v.6.11.1 (Google Cloud Functions)

Thanks!

UPDATE: I'm expecting to return data from this argument-function only if promise resolves without errors (i.e. reaches then), thus applying transaction only if user created.

Upvotes: 0

Views: 754

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317372

Promises can't be used inside a transaction handler. A transaction handler is required to immediately return the new contents of the database at the location of the transaction.

The call to transaction() itself returns a promise, so if you want to do something after a successful transaction, you can use then() on that promise (which contains the success state of the transaction) and follow up with some additional actions that could also return a promise from there.

Right now, it doesn't look like you're making any changes at all to the database within the transaction, so I'm curious why you're even using one.

Upvotes: 2

Related Questions