【问题标题】:Firebase Cloud Functions - How to wait for a function while within a exports?Firebase Cloud Functions - 如何在导出中等待函数?
【发布时间】:2019-09-17 02:28:58
【问题描述】:

使用 Firebase Cloud Functions 我正在尝试扩展 Firestore 文档中的 uri,并将其替换为扩展的 uri。

我正在使用运行良好的 tall npm 包 (https://www.npmjs.com/package/tall),但我无法将生成的扩展 uri 放入我的对象中以放回 firestore。

我相信它不会在我的其余函数完成之前返回,因此不会给我数据。当我尝试使用页面上的示例进行异步并使用 await firebase 时出现错误。

我假设我错过了一些非常简单的东西,但是在上传到云功能、测试和重试一天之后,我感到非常沮丧。

我错过了什么?

exports.addonSanitized = functions.firestore
  .document('addons/{addonId}')
  .onCreate(doc => {
    const addonId = doc.id;
    const addon = doc.data();

    const expandedLink = tall(addon.link)
      .then(unshortenedUrl => console.log('Tall url', unshortenedUrl))
      .catch(err => console.error('AAAW ????', err));

    const sanitized = {
      summary: `${expandedLink}`
    };

    return admin
      .firestore()
      .collection('addons')
      .doc(addonId)
      .update(sanitized)
      .then(doc => console.log('Entry Sanitized', doc));
  });

我希望扩展链接返回扩展链接。文档中输入的是[object Promise]

【问题讨论】:

    标签: javascript firebase async-await google-cloud-firestore google-cloud-functions


    【解决方案1】:

    您将获得“[object Promise]”,因为 expandedLink 的值是 Promise

    你真正想要的值是unshortenedUrl。您只能在 then() 存在的地方访问该值,因此您需要返回 tall Promise,并在 then() 中使用其他返回语句。

    可能是这样的(未经测试):

    exports.addonSanitized = functions.firestore
      .document('addons/{addonId}')
      .onCreate(doc => {
        const addonId = doc.id;
        const addon = doc.data();
    
        return tall(addon.link)
          .then(unshortenedUrl => {
            console.log('Tall url', unshortenedUrl)
            const sanitized = {
              summary: `${unshortenedUrl}`
            };
            return admin
              .firestore()
              .collection('addons')
              .doc(addonId)
              .update(sanitized)
              .then(doc => console.log('Entry Sanitized', doc));
          })
          .catch(err => console.error('AAAW ?', err));
    
      });
    

    【讨论】:

    • 感谢您的回复。我设法使用您的示例使其正常工作。稍后我仍然需要进行一些重构,但现在我能够解开这些链接。
    猜你喜欢
    • 2018-08-13
    • 2019-03-08
    • 2018-05-31
    • 2020-11-09
    • 2021-04-22
    • 2023-04-10
    • 1970-01-01
    • 2018-12-13
    • 2018-07-15
    相关资源
    最近更新 更多