简体   繁体   English

简短的if-else返回Javascript错误

[英]Short hand if-else returns error in Javascript

The following JS line of code is not working as I'd expect. 以下JS代码行无法正常运行。

When imageUrl has a value I get the following error and I expect notificationBody to be = "You received a new image message." 当imageUrl具有值时,出现以下错误,并且我希望notificationBody为=“您收到了新的图像消息。”

What am I missing here? 我在这里想念什么?

invalid value for the "notification.body" property. “ notification.body”属性的值无效。 Values must be strings. 值必须是字符串。

const notificationBody = (imageUrl === "" ? "You received a new image message." : messageTxt)

message payload: 消息有效负载:

const payload = {
            notification: {
              title: senderName + " sent you a message",
              body: notificationBody
            },

entire function: 整个功能:

exports.notifyNewMessage = functions.database.ref('/messages/{pushId}').onCreate((snap, context) => {

  const messageSnap = snap.val(); //snap.after.val();

  const fromId = messageSnap.fromId; 
  const toId = messageSnap.toId; 
  const messageTxt = messageSnap.message; 
  const imageUrl = messageSnap.imageUrl; 

  console.log('fromId: ', fromId);
  console.log('message: ', messageTxt);

  // Get the list of device notification tokens.
  const getDeviceTokensPromise = admin.database().ref('/fcmtokens/' + toId + '/registrationtokens').once('value');

  console.log('getDeviceTokensPromise', getDeviceTokensPromise);


  return admin.database().ref('/fcmtokens/' + toId + '/registrationtokens').once('value').then((userTok) => {

    const registrationTokens = Object.keys(userTok.val())

    console.log('registrationTokens', registrationTokens);


    return admin.database().ref('/users/' + fromId).once('value').then((userDoc) => {

      const user = userDoc.val(); //snap.after.val();

      const senderName = user.firstName //'Vanessa' //userDoc.firstName //get('firstName')
      console.log('senderName: ', senderName);

      const notificationBody = (imageUrl === "" ? "You received a new image message." : messageTxt)

      console.log('imageUrl: ', imageUrl);
      console.log('messageTxt: ', messageTxt);
      console.log('notificationBody: ', notificationBody);

        //build media messages notification
        const payload = {
            notification: {
              title: senderName + " sent you a message",
              body: notificationBody
            },
            data: {
              SENDER_NAME: senderName,
              SENDER_ID: fromId

            }//end data
        }//end payload

        //send message
        return admin.messaging().sendToDevice(registrationTokens, payload).then( response => {

          const stillRegisteredTokens = registrationTokens

          response.results.forEach((result, index) => {

                    const error = result.error

                    if (error) {

                        const failedRegistrationToken = registrationTokens[index]

                        console.error('blah', failedRegistrationToken, error)

                        if (error.code === 'messaging/invalid-registration-token' || error.code === 'messaging/registration-token-not-registered') {

                                const failedIndex = stillRegisteredTokens.indexOf(failedRegistrationToken)

                                if (failedIndex > -1) {
                                    stillRegisteredTokens.splice(failedIndex, 1)
                                }

                            }
                    }

                })//end forEach

                var  validTokens = {};

                stillRegisteredTokens.forEach(function(element){
                  console.log('valid token: ', element);
                  validTokens[element] = true;
                });
                //updates['registrationtokens'] = stillRegisteredTokens; ....update(updates);

                return admin.database().ref('fcmtokens/' + toId + '/registrationtokens').set(validTokens)

                // return admin.database().ref("fcmtokens/" + toId).update({
                //     //registrationTokens: stillRegisteredTokens
                // })//end update

        })//end sendToDevice


    })//end return-then

  })//end return-then

});

First, it looks like if imageUrl is not "" then notificationBody will be the value of messageTxt , not the "You received a new image message." 首先,如果imageUrl不是“”,则notificationBody将是messageTxt的值,而不是“您收到了新的图像消息”。 string. 串。

The javascript ternary statement works this way: javascript三元语句按以下方式工作:

const foo = (<conditional> ? <value if conditional is True> : <value if conditional is False>)

Second, are you sure your example code is exactly the same as the code you are getting the error with? 其次,您确定示例代码与发生错误的代码完全相同吗? I see no reference to notification.body in your example. 在您的示例中,我看不到对notification.body引用。

Your ternary isn't doing what you expect, the first case is for true, the second is for false, so you could either switch around your cases, or in my solution below, switch the comparison operator to !== 您的三元数未达到您的期望,第一种情况为true,第二种情况为false,因此您可以切换您的情况,或者在以下我的解决方案中,将比较运算符切换为!==

What I suspect is happening in your code, because your ternary is incorrect, is that you don't have a value set for messageTxt , and so it's passing undefined into your payload as the value of body 我怀疑代码中正在发生什么,因为您的三元数不正确,是您没有为messageTxt设置值,因此它会将undefined作为body的值传递给您的payload

I'd also highly suggest using JSON.stringify() around your payload if you're not doing that already. 我也强烈建议您在payload周围使用JSON.stringify()如果您尚未这样做的话)。

Solution

 const senderName = 'tacocat'; const imageUrl = 'something'; const messageTxt = 4815162342 const notificationBody = ( imageUrl !== "" ? "You received a new image message." : messageTxt ) const payload = JSON.stringify({ notification: { title: senderName + " sent you a message", body: notificationBody } }) console.log(payload) 

Documentation 文献资料

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

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

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