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

编程入门 行业动态 更新时间:2024-10-04 21:29:15

有<a href=https://www.elefans.com/category/jswz/34/1771182.html style=没有办法将 .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...

的文档

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

更多推荐

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

本文发布于:2024-05-30 23:38:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1771049.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:没有办法   promise

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!