Reputation: 115
I am currently trying to delay some actions with the cloud firestore but the setTimeout/setInterval doesn't seem to work for my code.
export const onTimerCreate = functions.firestore
.document("File/One")
.onCreate((snapshot, context) => {
setTimeout(countdown, 5000);
const messageData = snapshot.data()
const delay = countdown()
return snapshot.ref.update ({ delay : delay })
})
function countdown() {
return 0
}
I am trying to make sure the snapshot updates with a new value after that delay of 5 seconds but it just happens instantly every time... not sure what to do?
Upvotes: 0
Views: 665
Reputation: 317372
First thing's first - you can't delay a write to Firestore with Cloud Functions. I can't tell for sure if that's what you're trying to do here, but if so, you should give up that idea right now. Cloud Functions only trigger after some action has already taken place. You can't intercept a write. You can prevent a write with security rules, but security rules won't effectively allow you to delay the write. The write will happen as fast as possible.
Assuming that you do actually want to just do something in delay after the write occurs, you can use setTimeout, but be aware that you are paying for the CPU time associated with those 5 seconds.
Since background functions are required to return a promise that resolves only after all the background is complete, you need to create and arrange for that Promise to resolve after the timeout finishes, and after any other async work completes. Since you're using TypeScript (or at least you've tagged it here), async/await is the easiest way to get this done:
export const onTimerCreate = functions.firestore
.document("File/One")
.onCreate(async (snapshot, context) => {
await sleep(5000)
const messageData = snapshot.data()
await snapshot.ref.update ({ delay : delay })
})
async function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
Upvotes: 4