最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

有没有办法将 .then promise 添加到 for 循环?

网站源码admin32浏览0评论

有没有办法将 .then promise 添加到 for 循环?

有没有办法将 .then promise 添加到 for 循环?

我正在使用 Firebase 云函数为我提供的数组的每个元素更新字段值。

下面是我的循环。

我希望它在这个循环完成后立即将文档添加到另一个集合。

// FOR EACH ITEM
sortedArray.forEach(([key, val]) => {
    walletRef.doc('j10wmCUhUWPxYJpIElBxmFAEI6l1').update({
        [val.product]: admin.firestore.FieldValue.increment(val.quantity),
    })
})

当我尝试添加 .then 时,如下所示,它失败了

// FOR EACH ITEM
sortedArray.forEach(([key, val]) => {
    walletRef.doc('document_id_here').update({
        [val.product]: admin.firestore.FieldValue.increment(val.quantity),
    })
}).then((doc) => {
    logsRef.add({
        user_id: "document_id_here",
        product: items,
        transactionType: "purchase",
        date: new Date(),
    })
});

记录的错误:

textPayload: "Function execution took 2594 ms, finished with status: 'crash'"

字段值已更新,但未创建新文档。 请帮忙。 谢谢。

回答如下:

您的更新循环似乎没有必要,因为您正在对同一文档执行操作。

尝试这样的事情,一次设置多个属性

walletRef
  .doc("document_id_here")
  .update(
    Object.fromEntries(
      sortedArray.map(({ product, quantity }) => [
        product,
        admin.firestore.FieldValue.increment(quantity),
      ])
    )
  )
  .then((writeResult) => {
    // ...
  });

来自Increment a numeric value...

的文档

注意:如果字段不存在或者当前字段值不是数值,则操作将字段设置为给定值

发布评论

评论列表(0)

  1. 暂无评论