gpt4 book ai didi

javascript - fcm firebase 函数未定义值 - 第一次尝试,已定义 - 第二次尝试

转载 作者:太空宇宙 更新时间:2023-11-04 01:26:19 24 4
gpt4 key购买 nike

我有一个Android应用程序,我打算通过fcm实现发送通知。我已经为它编写了下面的 Javascript 代码,但是当我第一次尝试关注某人时,这些值是未定义的,但是,第二次它按预期完美工作......

Undefined first attempt

Defined second attempt

我尝试将这三个函数嵌套在一个函数中,也尝试在本地声明变量,但没有解决。


"use-strict"
const functions = require('firebase-functions');
const admin = require("firebase-admin");
admin.initializeApp();

var notificationDB;
var followedUserRef;
var followingUserRef;
var followingText;
var followingImageProfile;
var followedDToken_id;
var following;
var followingFullname;
exports.sendNotification =functions.database.ref("Notifications/{followed}/{notification_id}").onWrite((snapshot,context)=>{
const followed = context.params.followed;
const notification_id = context.params.notification_id;

notificationDB = admin.database().ref(`Notifications/${followed}/${notification_id}`);
console.log("Notification DB : "+notificationDB);
notificationDB.on("value",(snapshotOne)=>{
following = snapshotOne.val().userid;
followingText = snapshotOne.val().text;
});

followedUserRef = admin.database().ref(`Users/${followed}`);
followedUserRef.on("value",(snapshot)=>{
if(snapshot.val().token_id===null){
followedDToken_id = "null";
}else
followedDToken_id = snapshot.val().token_id;
});

followingUserRef = admin.database().ref(`Users/${following}`);
followingUserRef.on("value",(snapshot)=>{
followingFullname = snapshot.val().fullname;
followingImageProfile = snapshot.val().imageurl;
});

console.log("Following: "+following);
console.log("Followed: "+followed);
console.log("followed user Ref: "+followedUserRef)
console.log("NAME: "+followingFullname);
console.log("FOLLOWING TEXT: "+followingText);
console.log("tokken: "+followedDToken_id);
console.log("IMAGE: "+followingImageProfile);
});

第一次尝试时应显示预期结果,但第一次失败并在第二次获取值。

最佳答案

您的代码并未像您预期的那样完全按顺序执行,有请求发送到服务器,您需要在回调中执行控制台日志。例如这里

notificationDB = admin.database().ref(`Notifications/${followed}/${notification_id}`);
console.log("Notification DB : "+notificationDB);
notificationDB.on("value",(snapshotOne)=>{
following = snapshotOne.val().userid;
followingText = snapshotOne.val().text;
});

以下内容只会在响应时初始化,并在控制台登录后执行。因此,您需要根据以下原则重构代码:

  • 初始化变量
  • 然后调用发送请求的函数
  • 在回调中您执行控制台日志

使用 Promise API 会更优雅。

关于javascript - fcm firebase 函数未定义值 - 第一次尝试,已定义 - 第二次尝试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57408562/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com