3

I have a firebase function that is as follows:

exports.myFunction = functions.database.ref('/users/{id}/').onWrite((snapshot, context) => {

//do some processing here

//wait for 5 seconds

snapshot.after.ref.parent.once('value').then((newSnapshot) => {
    //do some processing here
    //check for some CONDITION
});

//do some processing here

return snapshot.after.ref.set(true); //return this if the CONDITION has been satisfied
return null;    //return this if the CONDITION check fails
});

I am unable to find a suitable implementation for this logic. I am running into two problems.

Firstly, I am not sure how to delay the execution by waiting for 5 seconds. I have tried implementing the setTimeout method but I am going wrong somewhere.

Secondly, I do not know how to program so that an appropriate return value is passed depending on the CONDITION check in the inner function.

It is my first time working on firebase and I am relatively new to js so any help would be appreciated.

EDIT:

Here is an example of what I am doing.

  1. Let us say there are two booleans internet and location_monitor. Both are true initially which has been set by the client. The location is being processed for some information. The client can set both to false at any time.

  2. Client loses internet connection. The variable internet is changed to false. The client is notified via a local monitoring service that internet connection has been lost.

  3. A timeout period is set for the client to come back online(5 seconds say). If the client comes online, location monitoring is reestablished and the processing continues. If the client does not come online, location monitoring is stopped. When the client comes online after a day or so, location monitoring is started as a fresh data set.

speedster01
  • 433
  • 3
  • 19
  • Please explain why you need to wait 5 seconds. Waiting for any reason is almost certainly not what you want to do in a Cloud Function. (Note also that it costs you money to run the function even if it's waiting.)\ – Doug Stevenson Jul 04 '18 at 06:03
  • @DougStevenson I have updated the question. – speedster01 Jul 04 '18 at 07:10
  • How would the Cloud Function know that the client lost internet connection? Client can't change variable internet to False since it doesn't have internet access. – LundinCast Jul 04 '18 at 11:06
  • @LundinCast Use the onDisconnect class. – speedster01 Jul 04 '18 at 11:13
  • I explain my problem in detail in this link. https://stackoverflow.com/questions/72780175/firebase-cloud-function-run-after-10-seconds – ursan526 Jun 28 '22 at 02:39

0 Answers0