【问题标题】:Cloud functions Error: function crashed out of request scope Function invocation was interrupted云函数错误:函数崩溃超出请求范围函数调用被中断
【发布时间】:2020-05-19 08:58:16
【问题描述】:

我在尝试向某些设备发送通知负载时随机收到此错误消息。 每 10 次成功尝试中可能会发生 1 次。

在云函数和 node.js 方面,我是一个完全的新手,希望它在我的代码中是一个愚蠢的简单错误,只是有时似乎会中断。

在搜索此错误消息时,我发现它可能会在通知发送之前完成功能。但我不确定如何尝试修复它。

任何人都可以使用以下功能指导我正确的方向...

    *** // // --------------------- new chat message function -------------------
  //
  exports.newChatMessage = functions.firestore
  .document('/notifications/{toUID}/newMessage/{docID}')
  .onCreate((snap, context) => {

  const toUser = context.params.toUID;
  const documentID = context.params.docID;
  const newValue = snap.data();
  const title = newValue.title;
  const content = newValue.content;
  const fromUID = newValue.senderUID;
  const senderFirstName = newValue.senderFirstName;
  const deviceToken = newValue.deviceToken;
  const senderThumbUrl = newValue.senderThumbUrl;
  const bigPictureUrl = newValue.bigPictureUrl;
  const messageType = newValue.messageType;
  const time = newValue.time_stamp;

  console.log('New chat message to : ', toUser);
  console.log('Message ID : ', documentID);
  console.log('Type : ', messageType);
  console.log('Message : ', content);
  console.log('Time Stamp : ', time);


  const payload = {
    data : {
      title : title,
      content : content,
      senderUID : fromUID,
      senderThumbUrl : senderThumbUrl,
      senderFirstName : senderFirstName,
      bigPictureUrl : bigPictureUrl,
      messageType : messageType,
      notificationType : 'newChatMessage'
    }
  };

  admin.messaging().sendToDevice(deviceToken, payload).then(response => {
  console.log('Notification sent successfully');

  const deleteDoc = db.doc(`notifications/${toUser}/newMessage/${documentID}`);
  deleteDoc.delete();
  console.log('Notification document deleted');

  return true;
  })
  .catch(err => {
  console.log('Error : Problem sending notification', err);
  return false;
  });
  return true;
  });
  //
  // // ----------------- END OF :  new chat message function -------------- ***

【问题讨论】:

    标签: javascript node.js google-cloud-functions


    【解决方案1】:

    当所有异步工作完成时,您不会返回一个解决方案。 This is required by Cloud Functions。不返回承诺意味着您的函数在工作完成之前正在清理。你应该做的是返回你开始的承诺链:

    return admin.messaging().sendToDevice(...).then(...).catch(...)
    

    你还需要从内部回调返回deleteDoc.delete()返回的promise,而不是return true

    了解如何在 Cloud Functions 中正确处理 JavaScript Promise 绝对是关键,因此如果您要继续使用它,我建议您研究一下它们是如何工作的,尤其是对于更复杂的任务。

    【讨论】:

    • 感谢您快速深入的回复,该链接也很有帮助,因为我想我现在开始理解它了。
    猜你喜欢
    • 1970-01-01
    • 2019-11-28
    • 2020-02-28
    • 1970-01-01
    • 2018-01-16
    • 1970-01-01
    • 2019-01-08
    • 1970-01-01
    • 2019-09-21
    相关资源
    最近更新 更多