简体   繁体   中英

Using async/await inside firebase cloud functions

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 {}
}

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 {}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM