SRR
SRR

Reputation: 1758

Firebase Cloud Function only works with console.log()

I've written a few cloud functions for my project so far. I was building a new function addUserToEmailLists and testing it to see if it got called simply by setting a field in a document when that document was created, onCreate()

exports.addUserToEmailLists = functions.firestore.document('Users/{userID}/jobPreferences/myPreferences').onCreate(() => {
  console.log('Function called!'); //remove this and it doesn't work
  return db.doc(`DatabaseInfo/accounts`).set({ //update the number of preferences
        preferencesSet: 1
  }).catch(error=>{
        console.log(error);
        return error;
  });
})

At first I had just from the line with return straight down in the function and the Firebase log kept saying the function was executed with status 200 but the document wasn't being set. Just as a last resort I added the console.log('Function called!'); and it worked! Then I removed the line and deployed once more and it failed to set the field accountsCreated (did that a couple more times waiting at least 3 minutes before trying to trigger the function again to be sure). My other functions don't have any console.log() statements so I'm at a loss for what causes this behaviour. Does anyone have a suggestion?

Upvotes: -1

Views: 190

Answers (1)

ostergaard
ostergaard

Reputation: 3507

Looks to me like you are calling an asynchronous function and expecting it to behave synchronously.

Perhaps the addition of a console.log entry simply gives the function the headroom it needs to complete the asynchronous work.

Try something like this:

exports.addUserToEmailLists = functions.firestore.document('Users/{userID}/jobPreferences/myPreferences').onCreate(async () => {
  await db.doc(`DatabaseInfo/accounts`).set({ //update the number of preferences
        preferencesSet: 1
  });
})

Upvotes: 1

Related Questions