Firebase Cloud Functions - 如何在导出过程中等待函数



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

我正在使用运行良好的高 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]",因为expandedLink的值是一个Promise

您实际想要的值是 unshortenedUrl 。您只能在该值所在的then()中访问该值,因此您需要改为返回 tall Promise,并将另一个 return 语句放在 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));
  });

最新更新