【发布时间】:2019-01-27 02:32:33
【问题描述】:
自从 Firebase Cloud Functions 支持节点 8 以来,我一直很高兴地使用 async/await。不过,我正在为一件事而苦苦挣扎。使用可调用函数时,被告知必须在函数中返回一个promise,否则将无法正常工作。使用原始承诺时,我很清楚如何使用它:
exports.createBankAccount = functions.region('europe-west1').https.onCall((data, context) => {
return promiseMethod().then((result) => {
return nextPromise(result);
}).then((result) => {
return result;
}).catch((err) => {
// handle err
})
});
但是现在,有了异步等待,我不确定如何返回这个“承诺链”:
exports.createBankAccount = functions.region('europe-west1').https.onCall(async (data, context) => {
const res1 = await promiseMethod();
const res2 = await nextPromise(res1);
return res2;
// ??? Where to return the promise?
});
有人知道吗?
【问题讨论】:
-
“我不知道如何返回这个“承诺链”:”——正如你在你编写的代码中所做的那样。
-
好的,但是 firebase 控制台上的日志告诉我,我调用了该函数 2 次,而实际上我只调用了 1 次。我认为这与以错误的方式返回这些承诺有关。
-
您可以轻松设置示例项目并验证答案的声明。只需创建一个等待 10 秒然后返回结果的函数。如果你用 await 调用这个函数,firebase 函数会正确等待 10 秒然后返回结果。
-
我已将 google-firebase 团队的权威代码示例添加到我的答案中。如果这还不足以支持它,我不知道。
标签: javascript firebase async-await google-cloud-functions