【问题标题】:How do I call a custom function from within another custom cloud function within my index.ts file?如何从我的 index.ts 文件中的另一个自定义云函数中调用自定义函数?
【发布时间】:2021-02-12 11:47:05
【问题描述】:

这里的总体目标是了解 Firebase 将如何向我收取函数调用的费用。我定义了一个名为newUserFlow 的虚拟函数和一个名为addFriend 的函数。如果我在addFriend 中调用newUserFlow,我想查看Firebase 控制台-> 云功能-> 使用选项卡是否会将其显示为调用了1 个函数或调用了2 个函数。但是,我不断收到错误消息。

exports.newUserFlow = functions.https.onCall((data, context) => {
  return 'finished new user flow';
});

exports.addFriend = functions.https.onCall((data, context) => {
  console.log('addFriend: ');
  const promise = exports.newUserFlow(null, null)
  // var outputVal: string;
  promise.then(async (outputVal: string) => { 
    console.log('addFriend_outputVal: ', outputVal)
    const uid1 = context?.auth?.uid; //current user 
    if (uid1) {
      var uid2: string;
      const docUID2 =  await admin.firestore().collection('users').where('username', '==', data.targetUser).get();
      const friendsColl = 'friends_' + uid1
      if (!docUID2.empty) {
        docUID2.forEach(doc => {
          uid2 = doc.get('uid').toString(); //target UID
          if (uid2) {
            const docRef = admin.firestore().collection(friendsColl).doc();
            return docRef.set({
              friendUID: uid2,
              stat: 0, //0 = blocked, 1 = accepted, 2 = pending, 3 = declined 
              createDate: admin.firestore.FieldValue.serverTimestamp(),
              modifiedDate: admin.firestore.FieldValue.serverTimestamp(),
            })
          }
          else {
            return console.log('addFriend_Error: Target uid is empty.');
          }
        })
      }
      else {      
        return console.log('addFriend_Error: Target user not found.');
      }
    }
    else {
      return console.log('Error: user is not authorized');
    }
  }
    
  )

  promise.catch((outputVal: string) => {
    return console.log('addFriend_promisecatch')
  })
  
});

必须正确处理错误承诺或使用void 运算符明确标记为已忽略

【问题讨论】:

    标签: typescript promise google-cloud-functions


    【解决方案1】:

    首先,不要将 Cloud Function 调用与 JavaScript(或 TypeScript)函数调用混淆。作为单个 Cloud Function 调用的一部分,您可以调用任意数量的 JS 函数。他们每次通话不收取额外费用。您只需为调用该函数所花费的额外总时间付费。

    其次,一个可调用类型的云函数调用第二个可调用云函数通常没有意义。如果您希望两个 Cloud Functions 共享某些功能,则它们应该调用共享的 JS 函数。

    exports.cloudFunction1 = functions.https.onCall((data, context) => {
        sharedJsFunction()
    });
    exports.cloudFunction2 = functions.https.onCall((data, context) => {
        sharedJsFunction()
    });
    
    function sharedJsFunction() {
    }
    

    关于不返回承诺的错误消息与上述所有内容完全无关。您将需要了解如何正确处理 Promise,并确保您的代码从顶级 Cloud Function 返回一个 Promise,该 Promise 使用对象解析以发送回客户端。现在,您的 addFriend 根本不返回任何内容。它的返回语句只从匿名回调函数async (outputVal: string) => {}返回,而不是主函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-11
      • 2017-03-17
      相关资源
      最近更新 更多