【问题标题】:Firebase Cloud Function, triggers onWrite method and getting problem in retrieving user data [closed]Firebase Cloud Function,触发 onWrite 方法并在检索用户数据时遇到问题 [关闭]
【发布时间】:2020-05-30 19:25:07
【问题描述】:

This is the cloud function that triggers when data is changed,created or deleted. 在这个函数中,我已经标记了代码,我想在其中检索存储在具有相同 ID 的实时数据库的另一个节点中的用户令牌。正如您在实时数据库中看到的那样。但我无法从数据库中获取令牌。请帮我解决这个问题。

This is Structure of my realtime database. 我想从这个云函数中的数据库中获取令牌

【问题讨论】:

  • 请编辑问题以显示所有相关代码在问题本身中。代码链接可能会随着时间的推移而失效,这将使这个问题在未来对其他人毫无用处。

标签: javascript firebase-realtime-database google-cloud-functions firebase-cloud-messaging android-push-notification


【解决方案1】:

once() 方法是异步的,并返回一个 Promise,但您无需等待该 Promise 解析即可获取节点的值。

由于您将 Cloud Function 声明为异步函数,因此以下内容应该可以解决问题

//...
const deviceTokenSnap = await admin.database().ref(`tokens/${userId}/token`).once('value');
const token = deviceTokenSnap.val();
//...

此外,建议避免将 async/await 与 then() 混合使用。

你应该如下调整函数的结尾:

const response = await admin.messaging().sendToDevice(...);
console.log(response);
return null;

您还应该使用 try/catch 块,请参阅 https://itnext.io/error-handling-with-async-await-in-js-26c3f20bc06a


最后,请避免添加 IDE 的屏幕截图,而是将代码复制/粘贴到您的问题中。

【讨论】:

    猜你喜欢
    • 2018-05-16
    • 1970-01-01
    • 1970-01-01
    • 2019-12-24
    • 2017-08-25
    • 1970-01-01
    • 2018-08-09
    • 1970-01-01
    • 2020-10-26
    相关资源
    最近更新 更多