没有办法将 .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 循环?
发布评论