简体   繁体   English

在 firebase 云函数中使用 async/await

[英]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:在 firebase 云函数中执行异步任务时,我是否需要await每个任务,如下例所示:

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).如果您不返回在所有工作完成后解决的承诺(当您正确使用 await 时,异步函数会这样做),那么异步工作很可能无法自行完成。

The documentation states:文档指出:

To return data after an asynchronous operation, return a promise.要在异步操作后返回数据,请返回一个 Promise。 The data returned by the promise is sent back to the client. Promise 返回的数据被发送回客户端。

One thing that was missing from your first code sample is the async keyword that would make await work correctly:您的第一个代码示例中缺少的一件事是使 await 正常工作的 async 关键字:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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