When performing asynchronous tasks inside a firebase cloud function do I need to await
for every task like the example below:
exports.function = functions.https.onCall(data,context)=>{ await db.doc('someCollection/someDoc').update({someField: 'someValue'}) await db.doc('someCollection/someDoc2').update({someField: 'someValue'}) await db.doc('someCollection/someDoc3').update({someField: 'someValue'}) return {} }
or can I just fire these asynchronous calls? given that I don’t need to return anything based on the data received from these tasks to the client like in the other example below:
exports.function = functions.https.onCall(data,context)=>{ db.doc('someCollection/someDoc').update({someField: 'someValue'}) db.doc('someCollection/someDoc2').update({someField: 'someValue'}) db.doc('someCollection/someDoc3').update({someField: 'someValue'}) return {} }
Advertisement
Answer
Yes, you need to wait for all asynchronous work to complete as part of executing your function. Async work will very likely not complete on its own if you don’t return a promise that resolves when all the work is done (which async functions do when you use await correctly).
The documentation states:
To return data after an asynchronous operation, return a promise. The data returned by the promise is sent back to the client.
One thing that was missing from your first code sample is the async keyword that would make await work correctly:
exports.function = functions.https.onCall(async (data,context) => { db.doc('someCollection/someDoc').update({someField: 'someValue'}) db.doc('someCollection/someDoc2').update({someField: 'someValue'}) db.doc('someCollection/someDoc3').update({someField: 'someValue'}) return {} }