dshukertjr
dshukertjr

Reputation: 18573

Firebase Cloud Functions sometimes not executing until the end of the function

If I have a cloud function like this, will the function setData() always execute until the end of the function(console either "successfully set data!" or "could not set data")? Because I have a function set up in a similar manner as this and it sometimes seems to stop executing in the middle of its execution.

function setData() {
  admin.database().ref(`someLocation`).set(true)
  .then(() => {
    return admin.database().ref(`anotherLocation`).set(true)
  }).then(() => {
    console.log("successfully set data!")
  }).catch(err => {
    console.log("could not set data", err)
  })
}


exports.newPotentialMember = functions.database.ref('listenLocation')
  .onCreate(event => {

    setData()

})

Upvotes: 2

Views: 1038

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598668

You're not returning any value from your newPotentialMember right now. That means that Cloud Functions can stop execution of your code as soon as newPotentialMember returns, which is straight after setData starts. Since writing to the database happens asynchronously, you have to return a promise from newPotentialMember that resolves after all writes have completed.

function setData() {
  return admin.database().ref(`someLocation`).set(true)
  .then(() => {
    return admin.database().ref(`anotherLocation`).set(true)
  })
}


exports.newPotentialMember = functions.database.ref('listenLocation')
  .onCreate(event => {
    return setData()
})

I recommend you carefully read the Firebase documentation on synchronous functions, asynchronous functions, and promises.

Upvotes: 7

Related Questions